使用jQuery:动态检查和取消选中复选框? [英] Check and Uncheck Checkbox Dynamically with jQuery : bug?

查看:162
本文介绍了使用jQuery:动态检查和取消选中复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个脚本,以控制主&

 <$ c 

$ c> $(document).ready(function(){

$('#myCheck')。click(function(){
$('。myCheck')。attr ';';'';'''');
'('。myCheck')。 check')){
$('#myCheck')。attr('checked',false);
} else {
$('#myCheck')。attr ,true); // IT不工作,为什么?
alert(Checkbox Master must be checked,but it's not!);
}
});

});

这是我的HTML:

 < input type =checkboxid =myCheckchecked =checked/>& nbsp;& nbsp; Checkbox Master< br / 
< input type =checkboxclass =myCheckvalue =1/>& nbsp;& nbsp;复选框Slave 1< br /
< input type =checkboxclass =myCheckvalue =1/>& nbsp;& nbsp; Checkbox Slave 2

查看我的简单 JsFiddle 来了解问题。



编辑1:像Inser说的,问题发生在jQuery 1.9.2及以上。没有更多的问题与jQuery 1.8.3。 Strange ...



编辑2: Inser找到解决方案,使用 .prop('checked',true)而不是 .attr('checked',true)。看看下面的注释...

解决方案

对新版本的jQuery使用prop方法:

  $('#myCheck')。prop('checked',true); 
$('#myCheck')。prop('checked',false);

http: //jsfiddle.net/uQfMs/37/


I made a script in order to control master & slave checkboxes (automatic checking and unchecking).

Here is my JS :

$(document).ready(function() {

    $('#myCheck').click(function() {
        $('.myCheck').attr('checked', false);
    });
    $('.myCheck').click(function() {
        if ($('.myCheck').is(':checked')) {
            $('#myCheck').attr('checked', false);
        } else {
            $('#myCheck').attr('checked', true); // IT DOESN'T WORK, WHY ?
            alert("Checkbox Master must be checked, but it's not!");
        }
    });

});

And here is my HTML :

<input type="checkbox" id="myCheck" checked="checked" />&nbsp;&nbsp;Checkbox Master<br />
<input type="checkbox" class="myCheck" value="1" />&nbsp;&nbsp;Checkbox Slave 1<br />
<input type="checkbox" class="myCheck" value="1" />&nbsp;&nbsp;Checkbox Slave 2

Look at my simple JsFiddle to understand the problem.

EDIT 1 : Like Inser said, the problem happens with jQuery 1.9.2 and over. No more problem with jQuery 1.8.3. Strange...

EDIT 2 : Inser found the solution, use .prop('checked', true) instead .attr('checked', true). Look at the comments below...

解决方案

Use prop method for new versions of jQuery:

$('#myCheck').prop('checked', true);
$('#myCheck').prop('checked', false);

http://jsfiddle.net/uQfMs/37/

这篇关于使用jQuery:动态检查和取消选中复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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