开发者问题收集

无法将属性“onclick”设置为 null(我已添加 id)

2017-04-19
58

我已经在 HTML 中为 JS 添加了 id,但是打开网站仍然显示错误:

Uncaught TypeError: Cannot set property 'onclick' of null

请帮忙。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="jquery-1.7.2.js" type="text/javascript"></script>
<script>
var btn = document.getElementById("btn");
btn.onclick = function() {
    var arrays = new Array();
    var items = document.getElementsByName("check");
    for(var i=0;i<items.length;i++) {
        if(items[i].checked) {
            arrays.push(items[i].value);`enter code here`
        }
    }
    alert("numbers checked:" + arrays.length);
}
</script>
</head>
<body>
<input type="checkbox" value="1" name="check" checked/>
<input type="checkbox" value="2" name="check"/>
<input type="checkbox" value="3" name="check" checked/>
<input type="button" value="numbers you have checked" id="btn"/>
</body>
</html>
2个回答

尝试一下

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>

<body>
    <input type="checkbox" value="1" name="check" checked/>
    <input type="checkbox" value="2" name="check" />
    <input type="checkbox" value="3" name="check" checked/>
    <input type="button" value="numbers you have checked" id="btn" />

    <script src="jquery-1.7.2.js" type="text/javascript"></script>
    <script>
        var btn = document.getElementById("btn");
        btn.onclick = function () {
            var arrays = new Array();
            var items = document.getElementsByName("check");
            for (var i = 0; i < items.length; i++) {
                if (items[i].checked) {
                    arrays.push(items[i].value);
                }
            }
            alert("numbers checked:" + arrays.length);
        }
    </script>
</body>

</html>
Mohamed Abbas
2017-04-19

不要使用输入,而是使用按钮。并调用以下函数:

<button id="btn" onclick="myFunction()">
adirocks27
2017-04-19