我只是想完全理解一个错误,因为有时候我可以绕过它,有时候我不能.我试过写一个函数:
function toggleButton() {
}
Run Code Online (Sandbox Code Playgroud)
但我得到了同样的错误.这是.js样本.
var checkBox = document.getElementById("chkMyBox");
checkBox.onclick = function toggleButton(e, obj1)
{
var btnElement = document.getElementById("btnMyButton");
if(btnElement != null) {
alert("Element not null");
if(e.target.checked && obj1 != null) {
alert("Checking check " + obj1.checked);
if(obj1.checked == true && btnElement.getAttribute('disabled') == false){
btnElement.getAttribute('disabled') = false;
} else {
btnElement.getAttribute('disabled') = true;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是html:
<form id="frmCheckBox">
<input type="checkbox" id="chkMyBox" />
<button id="btnMyButton" disabled>I'm a Button</button>
</form>
Run Code Online (Sandbox Code Playgroud)
小智 5
更改此行使用name:
<input type="checkbox" name="chkMyBox" />
Run Code Online (Sandbox Code Playgroud)
改为使用id:
<input type="checkbox" id="chkMyBox" />
Run Code Online (Sandbox Code Playgroud)
或者你可以使用:
var elements = document.getElementsByName('chkMyBox');
var element = elements[0]; //first element with that name in the array
Run Code Online (Sandbox Code Playgroud)
要么
var element = document.getElementsByName('chkMyBox')[0];
Run Code Online (Sandbox Code Playgroud)
更新(因为OP改变了原始问题的代码):
function toggleButton(e, obj1)
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为只有一个参数给回调函数(e).使用e.target获得的元素.