2016-02-13 38 views
1

我有一些复选框,我试图做一个反转功能,但我想影响除第一个复选框,所以我使用jQuery和研究后,我我知道我应该使用.not(':first'),但我不知道应该把它放在我已经写好的代码中。如何结合。每个与.not()

function invert(){ 
$('input[type="checkbox"]').each(function() { 
$(this).prop('checked', !$(this).is(':checked')); 
});} 

请问您能帮我吗?

+0

'$('input [type =“checkbox”]:not(:first)')'? – putvande

+0

是的,这也适用,很抱歉,但我是jQuery新手。 –

回答

4

有几种方法可以做到这一点,包括但不限于以下几点。

所有的选择:

$('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; 
}); 
1

尝试利用:gt()选择与放慢参数0到选择索引大于0的元素:第一个

$("input[type=checkbox]:gt(0)").each(function() { 
    // do stuff with `input` elements having index greater than `0` 
})