复选框上的javascript单击事件导致复选框未选中

时间:2014-05-30 13:47:51

标签: jquery asp.net checkbox webforms

您好,并提前感谢您给我的任何建议。

我有一个页面,其中包含一个带有HeaderTemplate复选框的gridview,以及下面几列中的复选框。不在HeaderTemplate中的所有复选框都有一个'selectCB'类。我在document.ready中创建了以下click事件,以便标题中的复选框可以用于检查all / uncheck all函数。复选框全部被选中时,每次都会取消选中Check All复选框本身,因此取消选中all的相反步骤永远不会完成。

我已经查看了SO上的一些帖子,herehere是一些例子,但到目前为止还没有任何工作。该页面现在正在使用jquery 1.6.1,因此在将来升级之前我只能使用这些选项。

这是点击功能:

    $('#cbAll').click(function() {
    event.preventDefault();
    event.stopPropagation();
    if ($('#cbAll').is(':checked')) {
        $('#gvCheckbox').find('td:first-child input[type="checkbox"]').each(function() {
            var cb = $(this);
            cb.attr('checked', true);
        });
        $(this).attr('checked', true);
    } else {
        $('#gvCheckbox').find('td:first-child input[type="checkbox"]').each(function() {
            var cb = $(this);
            cb.attr('checked', false);
        });
        $(this).attr('checked', false);
    }
    return false;
});

这是gridview的标题和列:

<asp:TemplateField>
    <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
    <HeaderTemplate>
        <input type="checkbox" id="cbAll" clientidmode="Static" />
    </HeaderTemplate>
    <ItemTemplate>
        <input type="checkbox" id="cbOne" clientidmode="Static" CssClass="selectCB" />
    </ItemTemplate>
</asp:TemplateField>

当我使用Chrome的调试器浏览此代码时,我看不到任何错误,直到完成处理代码后才会取消选中复选框。我尝试使用.live,它有相同的结果。我还能尝试什么?或者有人可以帮助弄清楚如何更有效地调试此问题以找到问题?

2 个答案:

答案 0 :(得分:4)

尝试使用change代替click,不要更改处理程序中的checked属性,使用prop代替attr,并为其添加参数事件对象。我也大大简化了这个功能。

$('#cbAll').change(function(e) {
    e.stopPropagation();

    $('#gvCheckbox')
        .find('td:first-child input[type="checkbox"]')
        .prop('checked', this.checked);
});

答案 1 :(得分:0)

为什么需要event.preventDefault()return false;

[event.preventDefault()]:如果调用此方法,则不会触发事件的默认操作。

[return false;]:调用时执行三个任务:

  1. event.preventDefault();
  2. event.stopPropagation();
  3. 停止回调执行并在调用时立即返回。
  4. 如果你只是评论这两种方法你的代码是有效的。 (PS:使用.prop()而不是.attr()):

    $(document).on('click','#cbAll',function(event) {
        //event.preventDefault();
        event.stopPropagation();
        if ($('#cbAll').is(':checked')) {
            $('#gvCheckbox').find('td:first-child input[type="checkbox"]').each(function() {
                var cb = $(this);
                cb.prop('checked', true);
            });
            $(this).prop('checked', true);
        } else {
            $('#gvCheckbox').find('td:first-child input[type="checkbox"]').each(function() {
                var cb = $(this);
                cb.prop('checked', false);
            });
            $(this).prop('checked', false);
        }
        //return false;
    });
    

    演示:

    http://jsfiddle.net/cbQt4/1/

相关问题