[英]when is checked attribute of check box element added to DOM?
I need to color all the check boxes that are checked to green and unchecked one's to red. 我需要将所有选中的复选框涂成绿色,将未选中的复选框涂成红色。
<style>
input[type=checkbox]+span{
color:red;
}
input[type=checkbox][checked]+span{
color:green;
}
</style>
<label>
<input type="checkbox" class="bike"/>
<span>I have a bike</span></label>
<label>
<input type="checkbox" checked class="car"/>
<span>I have a car</span>
</label>
It looks good when page is loaded. 加载页面时看起来不错。 But later, when user clicks on any check box,thier color is not being changed.After debugging, I came to know that checked
attribute is not added to input tag when user click happens. 但是后来,当用户单击任何复选框时,它们的颜色并没有改变。调试之后,我知道用户单击发生时, checked
属性没有添加到输入标签中。 Can somebody tell me the reason? 有人可以告诉我原因吗?
I tried to put checked
attribute explicitly then it worked well. 我试图显式地放置checked
属性,然后效果很好。
<button>Click</button>
<script>
$('button').click(function(){
$('.bike').attr('checked',true);
});
</script>
But I dont want to use any script to achieve this. 但是我不想使用任何脚本来实现这一目标。 Is there any way to make it possible? 有什么办法可以实现?
when actually the checked
attribute is added to check box to make it checked? 何时将checked
属性添加到复选框以使其选中? Here is the jsfiddle . 这是jsfiddle 。
There's a :checked
pseudo-selector ( updated fiddle ) 有一个:checked
伪选择器( 更新了小提琴 )
For completeness here's the current support for it: ( from MDN ) 为了完整性,这是当前的支持:( 来自MDN )
Chrome Firefox (Gecko) Internet Explorer Opera Safari
1.0 1.0 (1.7 or earlier) 9.0 9.0 3.1
This is nice function for this, by using some class: 通过使用一些类,这是一个很好的功能:
checkbox.on('click', function(){
$(this).toggleClass('checked');
if ($(this).hasClass('checked')) {
$(this).prop("checked", true);
}
else {
$(this).prop("checked", false);
}
});
For class checked
you can add some style like colors... 对于班级checked
您可以添加一些样式,例如颜色...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.