问题
I've a simple Select/Deselect option to check and uncheck checkboxes in my page. It works well, but only once. I don't know what's the problem for!
Please take a look at my codes. You can see its demo here.
HTML codes:
<input type="checkbox" id="main" />Select All<br />
<input type="checkbox" class="options" />Item 1<br />
<input type="checkbox" class="options" />Item 2<br />
<input type="checkbox" class="options" />Item 3<br />
<input type="checkbox" class="options" />Item 4<br />
jQuery code:
$('#main').click(function(e) {
$('.options').attr('checked', this.checked);
});
回答1:
You need to use .prop() instead of .attr()
Use
$('.options').prop('checked', this.checked);
A Good Read .prop() vs .attr()
来源:https://stackoverflow.com/questions/24910549/why-select-deselect-checkbox-works-only-once-with-jquery