jQuery / Javascript:对复选框和“checked”属性的点击事件 [英] jQuery/Javascript: Click event on a checkbox and the 'checked' attribute

查看:220
本文介绍了jQuery / Javascript:对复选框和“checked”属性的点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

$('input.media-checkbox').live('click', function(e){

    e.preventDefault();
    var that = $(this);

    if (that.attr('checked') == 'checked'){

        var m = that.attr('media');
        var mid = 'verify_' + m;
        that.parents('div.state-container').find('ul.' + mid).remove();
        that.attr('checked', false);
    } else {

        var url = AJAX_URL;

        $.ajax({
           type: 'GET',
           url: url,
           dataType: 'html',
           success: function(data){

                that.parents('li').siblings('li.verification').children('div.media-verification').append(data).fadeIn(500);
                that.attr('checked', 'checked');
           }
        }); 
    }

    return false;
});

我在表单中ajaxing,然后将相关复选框上的点击事件触发到另一个部分的ajax if必要。窗体被很好地插入,并且点击事件被触发,检查需要被检查和触发第二个ajax的框,因为复选框的 checked 属性最初是 false

I am ajaxing in a form, then firing the click event on relevant checkboxes to ajax in another partial if necessary. The form is inserted nicely, and the click events are fired, checking the boxes that need to be checked and firing the second ajax, since the checked attribute of the checkbox was initially false.

凝聚我的奶酪是什么,如果我UNCHECK其中一个盒子。尽管 e.preventDefault()检查属性设置为 false 在测试之前,因此如果语句总是执行 else 语句。我也试过这个与 $。is(':checked'),所以我完全不知道。

What's curdling my cheese is if I UNCHECK one of those boxes. Despite e.preventDefault(), the checked attribute is set to false BEFORE the test, so the if statement always executes the else statement. I've also tried this with $.is(':checked'), so I'm completely baffled.

看来unchecked - > checked状态读取原始状态,但选中 - > unchecked不会。任何帮助?

It appears that unchecked -> checked state reads the original state, but checked -> unchecked doesn't. Any help?

推荐答案

BE,我知道这是一年,但我认为我找到了解决方案,

B.E., I know it has been a year but I think I found the solution,

这里的问题是,click事件实际上被调用,并在checked属性被添加到复选框输入之前运行。所以函数运行,查看输入是否具有checked属性,并运行else条件。 THEN元素被赋予checked属性。

The issue here is that the click event actually get's called and runs BEFORE the "checked" property is added to the checkbox input. So the function runs, looks to see if the input has the "checked" attribute, and runs the else condition. THEN the element is given the "checked" property.

我刚刚跑到这里,我的解决方案是将函数绑定到更改函数,而不是点击

I just ran into this as well, and my solution was to bind the function to the change function rather than the click function, as change only fires AFTER the checked property has been updated on the input.

希望这可以帮助你,如果没有,任何人谁碰巧在这个帖子上发生了错误。同时遇到类似的问题。

Hopefully this help you, and if not, anyone else who happens to stumble upon this post while experiencing a similar issue.

这篇关于jQuery / Javascript:对复选框和“checked”属性的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆