代码之家  ›  专栏  ›  技术社区  ›  Brett

为什么我的元素为空?

  •  0
  • Brett  · 技术社区  · 14 年前

    为什么当我做一个 alert 它返回的值(见下文) null ? 当具有该ID的元素存在时?

    // make reference to divs
    var countdown_timer = document.getElementById("countdown_timer");
    var countdown_image = document.getElementById("countdown_image");
    
    // For element manipulation
    
    if (type == 'image') {
        var element = countdown_image;
    } else if (type == 'timer') {
        var element = countdown_timer;
    }
    
    alert(countdown_timer);
    

    div如下。。

    <div class="timer" id="countdown_timer"></div>
    
    3 回复  |  直到 12 年前
        1
  •  2
  •   Ben    14 年前

    javascript可能是在页面上的元素未加载之前执行的,因此选择器找不到任何东西。你的javascript是否高于 <body> 标签?试着把它放在后面 </body> 看看这对你有什么用。

    另一个解决方案是:

    window.onload = function () {
    //put all your JS here
    }
    
        2
  •  1
  •   meder omuraliev    14 年前
    onload = function() {
     // put you code here
    }
    
        3
  •  0
  •   Aaron    14 年前

    你的电话 document.getElementById 需要在div的标记之后。

    <div class="timer" id="countdown_timer"></div>
    <script type="text/javascript">
    var countdown_timer = document.getElementById("countdown_timer");
     ...
    </script>
    

    或者,可以使用window.onload事件,这是更好的方法。