选中和取消选中复选框并读取其状态
如何读取复选框的状态并将其状态设置为可见?我正在尝试这样的事情,但它总是返回 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>
How can I read the state of my checkbox and set it's state to be visible ? I'm trying 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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它是这样工作的:
});
我认为您无法选中该复选框,因为默认操作被阻止,即选中/取消选中该框,
这是我的想法:
该复选框最初未选中;
当您单击复选框时,会触发 click 事件,并且
varchecked
设置为 true;因为它设置为 true,所以
if(checked)
块将始终被执行;但您可能想知道为什么 UI 上未选中该复选框。我认为这是因为你设置了
e.preventDefault()
,它告诉复选框不受点击事件的默认行为的影响,即检查它;下次您再次检查时,会发生同样的事情。
It works this way:
});
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:
the checkbox is initially unchecked;
when you click the checkbox, the click event is fired, and the
var checked
is set to true;since it's set to true, the
if(checked)
block will always be executed;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;the next time you check it again, same thing will happen.
如果您使用 .change() 事件而不是 .clecked() 事件,也许这会更清楚。
您是说,当单击复选框时,如果checked==true,则设置checked=true,因此如果您从选中状态开始,则 false 部分将永远不会被执行。如果您一开始将其设置为 false,情况也是如此。
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.