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

javascript-选中/取消选中任何复选框时触发事件,javascript,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 b

在我的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!”);“
”会非常麻烦。)

如果没有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');
    });
}
//获取页面上的所有复选框
var checkbox=document.querySelectorAll('input[type=checkbox]);
//添加更改事件侦听器
对于(变量i=0;i
注意:
document.querySelectorAll
在IE7或更低版本中不受支持


单击在文档中冒泡,您可以为这些
输入的父元素使用单个eventlistener。大概是这样的:

<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>
如果没有
表单
或任何其他公共父元素(并且不想添加),也可以将侦听器添加到
文档

.

您可以这样做:

HTML:


检查我!
也检查我!
也检查我!
这是一个复选框。
这不是一个单选按钮。
只是说说而已。
JS:

var cbobject=document.forms[0].elements.checkbox;
对于(var i=0,len=cbobject.length;i
document.getElementById('form').addEventListener('click', function (e) {
    if (e.target.type === 'checkbox') {
        alert('Checkbox');
    }
});
<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>
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!!!")
}