gpt4 book ai didi

javascript - jquery多复选框问题

转载 作者:行者123 更新时间:2023-11-28 20:08:41 26 4
gpt4 key购买 nike

我正在尝试在表格中添加多个复选框。

这是代码。

HTML

<HTML>
<HEAD>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<TITLE>Multiple Checkbox Select/Deselect - DEMO</TITLE>
</HEAD>
<BODY>
<H2>Multiple Checkbox Select/Deselect - DEMO</H2>
<table border="1">
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>Cell phone</th>
<th>Rating</th>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="3"/></td>
<td>Droid X</td>
<td>4.5/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="4"/></td>
<td>HTC Desire</td>
<td>3/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="5"/></td>
<td>Apple iPhone 4</td>
<td>5/5</td>
</tr>
</table>

</BODY>
</HTML>

jQuery

<SCRIPT language="javascript">
$(function(){

// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});

// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){

if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}

});
});
</SCRIPT>

好吧,这工作正常,但问题是,我要做的不是静态表。

它请求和响应并动态附加表格。

如果行是这样添加的。它不处理该事件。

有什么好主意吗?

最佳答案

您需要使用event delegation

 // add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').prop('checked', this.checked);
});

// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(document).on('click', ".case", function () {
$("#selectall").prop("checked", $(".case:not(:checked)").length == 0);
});

演示:Fiddle

也可以使用.prop()设置选中状态

关于javascript - jquery多复选框问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20282241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com