[英]Add style on parent element of multiple set of radio buttons when checked without using jquery
[英]jquery radio buttons :checked and $(this).parent
页面加载时,默认情况下选中单选按钮。 我希望环绕此单选按钮的标签具有添加的CSS类。
我的代码有什么问题?
JSFIDDLE: http : //jsfiddle.net/3ar43086/4/
$(document).ready(function() {
if ($('input[type=radio]').is(':checked')) {
$(this).parent('label').addClass('checked'); }
});
<label for="myRadio"><input type="radio" id="myRadio" value="Example Radio Button" name="amount" checked>Example Radio Button</label>
.checked { background: yellow; }
代码中的$(this)
引用document
而不是input
。
可以解决此问题:
$(document).ready(function() {
if ($('input[type=radio]').is(':checked')) {
$('input[type=radio]').parent('label').addClass('checked');
}
});
您也可以这样:
$(document).ready(function() {
$('input[type=radio]:checked').parent('label').addClass('checked');
});
下一行中的this
是指window
$(this).parent('label').addClass('checked');
您应该这样做:
$(document).ready(function() {
var myInput = $('input[type=radio]');
if (myInput.is(':checked')) {
myInput.parent('label').addClass('checked'); }
});
或者,如果您要处理页面上的所有input
,请执行以下操作:
$(document).ready(function() {
$('input[type=radio]').each(function(){
if ($(this).is(':checked')) {
$(this).parent('label').addClass('checked');
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.