jquery切换事件与复选框值相混淆 [英] Jquery toggle event is messing with checkbox value

查看:100
本文介绍了jquery切换事件与复选框值相混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  $(

使用Jquery的切换事件来执行一些操作。 'input#myId')。toggle(
function(){
// do stuff
},
function(){
//做其他的东西
}
);

问题在于当我点击复选框时,复选框未被勾选。 (所有我已经放入切换事件的东西都能正常工作。)



我试过以下内容:

  $('input#myId')。attr('checked','checked'); 

  $(this).attr('checked','checked'); 

甚至只是简单的

 返回true; 

但没有任何效果。任何人都可以告诉我我要去哪里吗?



编辑 - 感谢所有回复的人。除了检查属性的部分,Dreas的回答几乎对我来说很有效。这完美的工作(虽然它有点hacky)

  $('input#myInput')。change(function()
{
if(!$(this).hasClass(checked))
{
//如果复选框未被选中,则执行
$(this) .addClass(checked);
return;
}

//如果复选框没有被选中,可以做些什么
$(this).removeClass('勾选');
});

再次感谢所有回覆。

解决方案

使用更改事件而不是切换事件,如下所示: ($(this))。

  $('input#myId')。 attr(checked)){
//做'check'

return;
}
时你会做的事情//这里做的东西你想在'未选中'时执行
});


I'm using Jquery's toggle event to do some stuff when a user clicks a checkbox, like this:

$('input#myId').toggle(
function(){
//do stuff  
},
function(){
//do other stuff    
}
);

The problem is that the checkbox isn't being ticked when I click on the checkbox. (All the stuff I've put into the toggle event is working properly.)

I've tried the following:

$('input#myId').attr('checked', 'checked');

and

$(this).attr('checked', 'checked');

and even simply

return true;

But nothing is working. Can anyone tell me where I'm going wrong?

Edit - thanks to all who replied. Dreas' answer very nearly worked for me, except for the part that checked the attribute. This works perfectly (although it's a bit hacky)

$('input#myInput').change(function ()
{
    if(!$(this).hasClass("checked"))
    {
        //do stuff if the checkbox isn't checked
        $(this).addClass("checked");
        return;
    }

    //do stuff if the checkbox isn't checked
    $(this).removeClass('checked');
});

Thanks again to all who replied.

解决方案

Use the change event instead of the toggle event, like such:

$('input#myId').change(function () {
    if ($(this).attr("checked")) {
        //do the stuff that you would do when 'checked'

        return;
    }
    //Here do the stuff you want to do when 'unchecked'
});

这篇关于jquery切换事件与复选框值相混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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