Javascript, innerHTML and getElementById



我是javascript的新手,一个朋友帮助我解决了这个问题,我知道它的作用,但我无法真正理解某些部分,我在代码中做了一些评论,有一些问题,我希望你能回答它们。

<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 函数返回具有指定 ID 的 html 元素,而 innerHtml 允许您编辑与该元素关联的 HTML

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

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

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

与 相同 document.getElementById("resultat").innerHTML = resultat;

对象是从你的对象函数返回的,你的函数只是从 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);
                }

最新更新