【问题标题】:Javascript, innerHTML and getElementByIdJavascript、innerHTML 和 getElementById
【发布时间】:2013-12-28 19:04:10
【问题描述】:

我对 javascript 完全陌生,一个朋友帮我解决了一个问题,我知道它的作用,但我不能真正理解某些部分,我在代码中做了一些 cmets 有一些问题希望你能回答他们。

<html>
<head>
    <title>Uppgift 15</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script>
            var  resultat = 0;

            function addera(){

                var t1 = Math.round(object("t1").value);

                if (t1 != 0){
                    resultat += t1;
                    object("t1").value = ""; 
                }
                else{
                    object("resultat").innerHTML = resultat; // where does "object" come from, what does innerHTML do?
                }
            }

            function object(id){ // i dont get this at all what does this do is there any other way to return?
                return document.getElementById(id);
            }
    </script>
</head>
<body>
    <form>
        <input id="t1">
        <input type="button" onClick=addera() value="resultat">
        <p id="resultat"></p>
    </form>
</body>
</html>

【问题讨论】:

  • object 只是一个返回元素的函数。
  • 它看起来像你的编程新手,不仅仅是 javascript ;)

标签: javascript innerhtml getelementbyid


【解决方案1】:

object 函数返回具有指定 ID 的 html 元素,而 innerHtml 允许您编辑与该元素关联的 HTML

【讨论】:

    【解决方案2】:

    object() 已在您的代码中定义,其中document.getElementById(id); 将返回具有指定 ID 的元素。

    innerHTML 属性设置或返回元素的内部 HTML。

    这里object("resultat").innerHTML = resultat;

    document.getElementById("resultat").innerHTML = resultat;

    【讨论】:

      【解决方案3】:

      对象是从你的对象函数返回的,你的函数只是从 dom 中通过 id 获取元素并返回它

      var  resultat = 0;
      
                      function addera(){
      
                          var t1 = Math.round(object("t1").value);
      
                          if (t1 != 0){
                              resultat += t1;
                              object("t1").value = ""; 
                          }
                          else{
                              object("resultat").innerHTML = resultat; // object is returned from     object function according to parameter of function the function takes this parameter as id
          and selects the element from dom 
      
                          }
                      }
      
                      function object(id){  
                          return document.getElementById(id);
                      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 2011-09-24
        • 2014-06-25
        • 1970-01-01
        相关资源
        最近更新 更多