我需要知道何时选中页面上的任何复选框:
e.g.
<input type="checkbox">
我在 Jquery 中尝试过这个
$('input type=["checkbox"]').change(function(){
alert('changed');
});
但它不起作用,有什么想法吗?
Use the change()
事件,以及is()
test:
$('input:checkbox').change(
function(){
if ($(this).is(':checked')) {
alert('checked');
}
});
由于我愚蠢地依赖 jQuery(在if
)当 DOM 属性同样合适并且使用起来也更便宜时。此外,选择器也已更改,以便在支持它的浏览器中将其传递到 DOMdocument.querySelectorAll()
method:
$('input[type=checkbox]').change(
function(){
if (this.checked) {
alert('checked');
}
});
为了完整起见,同样的事情也可以在纯 JavaScript 中轻松实现:
var checkboxes = document.querySelectorAll('input[type=checkbox]'),
checkboxArray = Array.from( checkboxes );
function confirmCheck() {
if (this.checked) {
alert('checked');
}
}
checkboxArray.forEach(function(checkbox) {
checkbox.addEventListener('change', confirmCheck);
});
参考:
- JavaScript:
-
Array.from() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from.
-
Array.prototype.forEach() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach.
-
document.querySelectorAll() https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll.
-
EventTarget.addEventListener() https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener.
- jQuery:
-
:checked http://api.jquery.com/checked-selector/.
-
change() http://api.jquery.com/change/.
-
is() http://api.jquery.com/is/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)