开发者

JQuery checkbox state is updated differently between group click() and $.each(obj.click())

开发者 https://www.devze.com 2023-01-01 09:09 出处:网络
The code below doesn\'t work in the same behavior. The sequence of click event and calling foo() is different. I want to know why they behave different sequence between call click() and iterate the ob

The code below doesn't work in the same behavior. The sequence of click event and calling foo() is different. I want to know why they behave different sequence between call click() and iterate the objects before call click() on each.

<script type="text/javascript">

      function foo(obj){
        alert(obj.id+" ->"+obj.checked);
      }

      function clickAll(val){
        if (val) {
          $(":checkbox").click();
        } else {
          $(":checkbox").each(function(开发者_如何学编程i,obj){
              obj.click();
              });
        }
      }
    </script> 
  </head>
<body>
<input type="checkbox" id="check1" onclick="foo(this)" /> a
<input type="checkbox" id="check2" onclick="foo(this)" /> b
<input type="checkbox" id="check3" onclick="foo(this)" /> c
<input type="button" onclick="clickAll(true)" value="click all" />
<input type="button" onclick="clickAll(false)" value="click all each" />
</body>


Instead of…

$(":checkbox").each(function(i,obj){
 obj.click();
});

Try:

$(':checkbox').each(function() {
 $(this).click();
});


$(":checkbox").each(function(i,obj){ // i is an index and obj is a dom element object... 
    //obj.click();  not a jQuery Object that is why it's not working as expected
    $(obj).click(); // do this instead..
});
0

精彩评论

暂无评论...
验证码 换一张
取 消