jquery多个复选框问题

时间:2013-11-29 09:24:56

标签: javascript jquery

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

这是代码。

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>

好的,这很好,但问题是,我要做的不是静态表。

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

如果像这样添加行。它没有处理这个事件。

有什么好主意吗?

3 个答案:

答案 0 :(得分:3)

您需要使用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()设置选中状态

答案 1 :(得分:0)

Jquery支持事件delegation,就像这样:

$(document.body).on('click', '.case', function(){

});

答案 2 :(得分:0)

使用.on()函数。示例可以在http://api.jquery.com/on/

中找到
相关问题