如何全局获取一次HTML元素并多次使用它?

kis*_*pit 1 javascript

我不想调用

        var element = document.getElementById('ph');
Run Code Online (Sandbox Code Playgroud)

每次UpdateClock为了效率而被召唤.所以我试图把它放在全球而不是放在里面UpdateClock.但是,它不起作用.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>This is a title</title>
    <script>
        var element = document.getElementById('ph');

        function UpdateClock() {
            var now = new Date();
            var hours = now.getHours();
            var minutes = now.getMinutes();
            var seconds = now.getSeconds();

            if (hours < 10)
                hours = "0" + hours;
            if (minutes < 10)
                minutes = "0" + minutes;
            if (seconds < 10)
                seconds = "0" + seconds;
            element.innerHTML = hours + ":" + minutes + ":" + seconds;
        }

    </script>

</head>
<body onload="setInterval('UpdateClock()', 1000)">
    <h1 id="ph"></h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

怎么了?这里有什么我想念的吗?

Que*_*tin 5

将元素添加到DOM 后,需要运行执行赋值的代码.

最简单的方法是:

<h1 id="ph"></h1>
<script>
    var element = document.getElementById('ph');
</script>
Run Code Online (Sandbox Code Playgroud)

或者,使用在添加元素后运行的事件处理程序.

<script>
    var element;
    addEventListener('load', function () {
        element = document.getElementById('ph');
    });
</script>
Run Code Online (Sandbox Code Playgroud)