我有下面的代码:
js:
$('[id^="check-"]').change(function(){
var new_id = this.id.replace(/check/, 'new'),
real_id = this.id.replace(/check/, 'real');
if ($(this).is(':checked')) {
$('#'+real_id).val($('#'+new_id).text());
} else {
$('#'+real_id).val(0);
}
});html:
<tr>
<td><span id="new-1">2</span></td>
<td><input type="text" name="real-1" id="real-1" value="0"></td>
<td><input type="checkbox" class="card" id="check-1"></td>
</tr>
<tr>
<td><span id="new-2">7</span></td>
<td><input type="text" name="real-2" id="real-2" value="0"></td>
<td><input type="checkbox" class="card" id="check-2"></td>
</tr>
<tr>
<td><span id="new-3">4</span></td>
<td><input type="text" name="real-3" id="real-3" value="0"></td>
<td><input type="checkbox" class="card" id="check-3"></td>
</tr>主要思想:当你点击related check-*复选框时,从new-*获取文本并将其放入real-*收件箱。
现在,我想添加另一个复选框,该复选框将对所有元素批量执行此操作。我试过了:
$('#main-checkbox').change(function(){
if ($(this).is(':checked')) {
$('.card').attr('checked', true);
} else {
$('.card').attr('checked', false);
}
});但它不起作用。为什么?如何为所有这些签出启动change操作。
谢谢。
发布于 2012-03-25 07:58:20
通过JavaScript更改字段值(包括选中状态)不会触发更改事件,但您可以显式调用.change()方法。你的函数也可以简化--你实际上不需要if/else结构:
$('#main-checkbox').change(function(){
$('.card').attr('checked', this.checked).change();
});演示:http://jsfiddle.net/4qs4d/
请注意,$(this).is(':checked')只是this.checked的一种缓慢的表达方式。此外,如果您使用的是jQuery 1.6或更高版本,则应该使用.prop() method而不是.attr()。
https://stackoverflow.com/questions/9856691
复制相似问题