我有一些复选框,我正在尝试制作一个反转函数,但我想影响除第一个复选框以外的所有复选框,所以我正在使用 jQuery,经过研究我明白我应该使用 .not(':first '), 但我不知道将它放在我已经编写的代码中的什么位置。
function invert(){
$('input[type="checkbox"]').each(function () {
$(this).prop('checked', !$(this).is(':checked'));
});}
你能帮帮我吗?
最佳答案
有几种方法可以做到,包括但不限于以下几种。
全部在选择器中:
$('input[type="checkbox"]:not(:first)').each(...)
随着.not()
method :
$('input[type="checkbox"]').not(':first').each(...)
随着.slice()
method :
$('input[type="checkbox"]').slice(1).each(...)
请注意,实际选中/取消选中复选框的行可以简化为:
this.checked = !this.checked;
但是,如果您在循环中所做的唯一事情是更改选中的属性,那么您不需要 .each()
,您可以改为 pass a function to prop()
:
$('input[type="checkbox"]:not(:first)').prop("checked", function(i, val) {
return !val;
});
关于javascript - 如何结合 .each 与 .not(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386703/