开发者

Check and uncheck checkbox and read its state

How can I read the state of my checkbox and set it's state to be visible ? I'm try开发者_StackOverflow社区ing something like this, but it always returns true:

 $('.show-check').live('click', function(e) {
    e.preventDefault();

    var checked = ($(this).is(':checked'));
    if(checked == true){
       $(this).attr('checked', true); 
    }
    else{
        $(this).attr('checked', false);
    }
 });


    <li>
        <img src="" class="show-image"/>
        <span class="show-title"></span>
        <input type="checkbox" class="show-check" />
    </li>


It works this way:

 $('.show-check').live('click', function() {


var checked = ($(this).is(':checked'));

if(checked){
   $(this).attr('checked', true);
}
else{
    $(this).attr('checked', false);
}

});

I think you couldn't check the checkbox because the default action is prevented, which is to check/uncheck the box

Here's my thought:

  1. the checkbox is initially unchecked;

  2. when you click the checkbox, the click event is fired, and the var checked is set to true;

  3. since it's set to true, the if(checked) block will always be executed;

  4. but you may wonder why the checkbox is not checked on the UI. I think it's because you set e.preventDefault() which tells the checkbox not to be affected by the default behaviour of click event, which is to check it;

  5. the next time you check it again, same thing will happen.


Maybe this would be clearer if you used the .change() event instead of the .clecked() event.

You are saying when the check box is clicked, if checked==true than set checked = true, so the false part will never be executed if you start with it checked. The same is true if you start with it set to false.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜