默认情况下,页面加载时会选中单选按钮。我希望环绕此单选按钮的标签添加一个 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');
});
关于javascript - jquery 单选按钮 :checked and $(this). 父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27003755/