javascript - 选中/取消选中任何复选框时触发事件

时间:2014-04-10 08:34:34

标签: javascript

在我的HTML中,我有很多复选框。

<input type="checkbox"> Check me! 
<input type="checkbox"> Check me as well!
<input type="checkbox"> Check me too! 
<input type="checkbox"> This is a checkbox.
<input type="checkbox"> It is not a radio button.  
<input type="checkbox"> Just saying.  

(Even more checkboxes ..............)

如果没有jQuery,如何更改文档中的任何复选框后如何创建警报?

(有这么多复选框,在每个复选框上添加onclick="alert('Hello!');"会非常麻烦。)

3 个答案:

答案 0 :(得分:8)

如果没有jQuery,你就会这样做:

// get all the checkboxes on the page
var checkboxes = document.querySelectorAll('input[type=checkbox]');

// add a change event listener
for(var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].addEventListener('change', function(){
        console.log('the checkbox changed');
    });
}

注意:IE7或更低版​​本不支持document.querySelectorAll

http://caniuse.com/queryselector

答案 1 :(得分:2)

点击正在文档中冒泡,您可以使用单个eventlistener作为这些input的父元素。像这样:

<form id="form">
    <input type="checkbox"> Check me!
    <input type="checkbox"> Check me as well!
    <input type="checkbox"> Check me too!
    <input type="checkbox"> This is a checkbox.
    <input type="checkbox"> It is not a radio button.
    <input type="checkbox"> Just saying.
</form>

JS:

document.getElementById('form').addEventListener('click', function (e) {
    if (e.target.type === 'checkbox') {
        alert('Checkbox');
    }
});

如果您没有form或任何其他常见的父元素(并且您不想添加一个),您也可以将监听器添加到document。< / p>

A live demo at jsFiddle

答案 2 :(得分:1)

你可以这样做:

HTML:

<form id="form">
    <input type="checkbox" name="checkbox" /> Check me!
        <input type="checkbox" name="checkbox"/> Check me as well!
        <input type="checkbox" name="checkbox"/> Check me too!
        <input type="checkbox" name="checkbox"/> This is a checkbox.
        <input type="checkbox" name="checkbox"/> It is not a radio button.
        <input type="checkbox" name="checkbox"/> Just saying.
</form>

JS:

var cbobject= document.forms[0].elements.checkbox;
for (var i=0, len=cbobject.length; i<len; i++) {
        if ( cbobject[i].type === 'checkbox' ) {
            cbobject[i].onclick = show_alert;
        }
    }
function show_alert(e){
    alert("checkbox!!!")
}

<强> DEMO

相关问题