在我的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 ..............)
Run Code Online (Sandbox Code Playgroud)
如果没有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');
});
}
Run Code Online (Sandbox Code Playgroud)
注意:document.querySelectorAllIE7或以下版本不支持.
http://caniuse.com/queryselector