Javascript onclick事件无效

时间:2014-10-04 06:37:03

标签: javascript events

运行下面的代码,得到以下错误 - “未捕获的TypeError:无法设置属性'onclick'of null”

<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById("x").onclick = function() {
alert("clicked the button");
};
</script>
</head>
<body>
<button id="x">this is button</button>
</body>
</html>

4 个答案:

答案 0 :(得分:2)

您无法通过id获取元素,因为未加载文档。

尝试添加onload函数:

window.onload = function() {
  document.getElementById("x").onclick = function() {
    alert("clicked the button");
  };
};

答案 1 :(得分:1)

您在DOM中存在按钮之前尝试绑定click事件。将您的点击事件绑定移动到身体的底部,按如下方式更改它:

<button id="x" onClick="alert('clicked the button');">this is button</button>

干杯, autoboxer

答案 2 :(得分:0)

您需要设置一个事件监听器:

var button = document.getElementById('x');

button.addEventListener('click', function() {
    console.log('button clicked');    
});

答案 3 :(得分:0)

您需要在<script>之后迁移<button>元素。引发错误是因为getElementById返回null,因为找不到元素#x,因为此时尚未达到button#x元素。

<!DOCTYPE html>
<html>
    <head>
    </head>
<body>
    <button id="x">this is button</button>
    <script>
       document.getElementById("x").onclick = function() {
           alert("clicked the button");
       };
    </script>
</body>
</html>