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..
});
精彩评论