Jquery 切换事件与复选框值混淆

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/355638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:01:18  来源:igfitidea点击:

Jquery toggle event is messing with checkbox value

jqueryforms

提问by John McCollum

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

当用户单击复选框时,我正在使用 Jquery 的切换事件执行一些操作,如下所示:

$('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)

编辑 - 感谢所有回复的人。除了检查属性的部分外,Dreas 的回答几乎对我有用。这完美地工作(虽然它有点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.

再次感谢所有回复的人。

回答by Andreas Grech

Use the changeevent instead of the toggleevent, like such:

使用change事件而不是toggle事件,例如:

$('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'
});

回答by dubek

While using the changeevent handler suggested by Dreas Grech is appropriate, it doesn't work well in IE 6 & 7, which doesn't fire the changeevent until the focus is blurred (that is, until you click outside the area of the checkbox). As QuirksModesay, "it's a serious bug".

虽然使用changeDreas Grech 建议的事件处理程序是合适的,但它在 IE 6 和 7 中不能很好地工作,它change在焦点模糊之前不会触发事件(即,直到您在复选框区域外单击) . 正如QuirksMode所说,“这是一个严重的错误”。

You might want to use the clickevent handler, but that won't work with keyboard navigation. You need to register a keyuphandler too...

您可能想要使用click事件处理程序,但这不适用于键盘导航。你也需要注册一个keyup处理程序......

See also this related question.

另请参阅此相关问题

I haven't yet found a good cross-browser solution that supports both mouse clicks and keyboard activation of the checkboxes (and doesn't fire too many events).

我还没有找到一个好的跨浏览器解决方案,它支持鼠标点击和复选框的键盘激活(并且不会触发太多事件)。



Regarding your solution for checking whether the checkbox is checked or not, instead of adding your own checkedclass, you may use HTML's checkedattribute:

关于检查复选框是否被选中的解决方案checked,您可以使用 HTML 的checked属性,而不是添加自己的类:

$('input#myInput').change(function () {
    if ($(this).attr("checked")) {
        //do stuff if the checkbox is checked
    } else {
        //do stuff if the checkbox isn't checked
    }
});

Any browser sets the checkedattribute of an inputelement to the value "checked"if the checkbox is checked, and sets it to null(or deletes the attribute) if the checkbox is not checked.

如果选中复选框,任何浏览器都会将元素的checked属性设置为input值,"checked"如果未选中复选框,则将其设置为null(或删除该属性)。

回答by solsTiCe

why not using $.is() ?

为什么不使用 $.is() ?

$('input#myId').change(
    function() {
        if ($(this).is(':checked')) {
            // do stuff here 
        } else {
            // do other stuff here
        }
});

回答by Richard

This is an answer by MorningZ (I found it here) that makes totally sense:

这是 MorningZ 的回答(我在这里找到),完全有道理:

The part you are missing is that "checkbox" is a jQuery object, not a checkbox DOM object

您缺少的部分是“复选框”是一个 jQuery 对象,而不是复选框 DOM 对象

so:

所以:

checkbox.checkedsure would error because there is no .checkedproperty of a jQuery object

checkbox.checked肯定会出错,因为没有.checkedjQuery 对象的属性

so:

所以:

checkbox[0].checkedwould work since the first item on a jQuery array is the DOM object itself.

checkbox[0].checked会起作用,因为 jQuery 数组上的第一项是 DOM 对象本身。

So in your change()function you can use

所以在你的change()函数中你可以使用

$(this)[0].checked

回答by Harikrishnan

this worked for me............ check it

这对我有用…………检查一下

$(":checkbox").click(function(){
if($(this).attr("id").split("chk_all")[1])
 {
  var ty  = "sel"+$(this).attr("id").split("chk_all")[1]+"[]";
  if($(this).attr("checked"))
   {
    $('input[name="'+ty+'"]').attr("checked", "checked");
   }
  else
   {
    $('input[name="'+ty+'"]').removeAttr("checked");
   }
 }
})

回答by adam

$('input#myId').toggle(
  function(e){
    e.preventDefault();
    //do stuff      
    $(this).attr('checked', 'true');
  },
  function(e){
    e.preventDefault();
    //do other stuff        
    $(this).attr('checked', 'false');
  }
);

回答by adam

I did a similar approach but simply using the checked attribute such as

我做了一个类似的方法,但只是使用了检查属性,如

 //toggles checkbox on/off
    $("input:checkbox").change(
        function(){
           if(!this.checked){
             this.checked=true;
           }
           else{
             this.checked=false;
           }
         }
       );
 //end toggle

回答by adam

Try using a non-jquery function:

尝试使用非 jquery 函数:

function chkboxToggle() {
  if ($('input#chkbox').attr('checked'))
    // do something
  else
    // do something else
}

then in your form:

然后以您的形式:

<input id="chkbox" type="checkbox" onclick="chkboxToggle()" />

回答by Harikrishnan

Try:

尝试:

$(":checkbox").click(function(){
  if($(this).attr("checked"))
   {
    $('input[name="name[]"]').attr("checked", "checked");
   }
  else
   {
    $('input[name="name[]"]').removeAttr("checked");
   }
})

回答by philljohn

    $("input[type=checkbox][checked=false]")// be shure to set to false on ready
    $("input#Checkbox1").change(function() {
        if ($(this).attr("checked")) {
            $("#chk1").html("you just selected me")//the lable
        } else {$("#chk1").html("you just un selected me") }    
    });