我正在研究JavaScript并测试一个我认为可以阻止复选框被检查的函数(code sample):
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" charset="utf-8">
var myBox = document.getElementById('bike');
myBox.addEventListener('click', stopCheck, false);
function stopCheck(e){
e.preventDefault();
}
</script>
<form action="">
<input type="checkbox" name="vehicle" value="Bike" id="bike" >I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
</body>
</html>
但代码不起作用。在复选框更改选中状态后,可能会执行stopCheck。如何解决?
答案 0 :(得分:2)
答案 1 :(得分:1)
可能是因为当您使用document.getElementById时,Dom树尚未完全创建。 移动下面的脚本可能会有所帮助:
<form action="">
<input type="checkbox" name="vehicle" value="Bike" id="bike" >I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
<script type="text/javascript" charset="utf-8">
var myBox = document.getElementById('bike');
myBox.addEventListener('click', stopCheck, false);
function stopCheck(e){
e.preventDefault();
}
</script>
答案 2 :(得分:-1)
使用document.getElementsByName返回带有名称的元素数组,在本例中为复选框。
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script>
window.onload = function() {
var vehicle = document.getElementsByName("vehicle");
for(var i=0;i<vehicle.length;i++){
vehicle[i].onclick = function(e) {
e.preventDefault();
};
}
};
</script>
<form action="">
<input type="checkbox" name="vehicle" value="Bike" id="bike" >I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
</body>
</html>