Jquery 切换事件与复选框值混淆 [英] Jquery toggle event is messing with checkbox value
问题描述
我正在使用 Jquery 的切换事件在用户单击复选框时执行一些操作,如下所示:
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.)
我尝试了以下方法:
$('input#myId').attr('checked', 'checked');
和
$(this).attr('checked', 'checked');
甚至简单
return true;
但是没有任何效果.谁能告诉我哪里出错了?
But nothing is working. Can anyone tell me where I'm going wrong?
编辑 - 感谢所有回复的人.除了检查属性的部分外,Dreas 的回答几乎对我有用.这完美地工作(虽然它有点hacky)
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.
推荐答案
使用 change
事件代替 toggle
事件,例如:
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屋!