javascript - jquery 单选按钮 :checked and $(this). 父级

标签 javascript jquery

默认情况下,页面加载时会选中单选按钮。我希望环绕此单选按钮的标签添加一个 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/

相关文章:

javascript - 显示来自数据库的 optgroup 值

javascript - jquery-ui datepicker 更改 z-index

Javascript:如何分配给变量?

javascript - 使用 jQuery 和一些逻辑的 Twitter 消息

javascript - 滚动时淡入和淡出的图像(jquery)

php - 是否可以有一个带有 CSS Counter 增量值的文本框?

javascript - 在文本后保持相同的高度和宽度 ('' )

javascript - 相对于页面上滚动位置的视觉计数器

javascript - 灯箱画廊串联起来

javascript - 如何使用 Jquery 在 ASP.Net 中制作对话框?