繁体   English   中英

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

[英]javascript - Trigger event when any checkbox is checked/unchecked

在我的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');
    });
}

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

http://caniuse.com/queryselector

点击正在文档中冒泡,您可以使用单个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中。

jsFiddle的现场演示

你可以这样做:

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!!!")
}

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM