简体   繁体   English

jQuery单选按钮:checked和$(this).parent

[英]jquery radio buttons :checked and $(this).parent

The radio button is checked by default when the page loads. 页面加载时,默认情况下选中单选按钮。 I want the label that wraps around this radio button to have a CSS class added to it. 我希望环绕此单选按钮的标签具有添加的CSS类。

What's wrong with my code? 我的代码有什么问题?

JSFIDDLE: http://jsfiddle.net/3ar43086/4/ 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) in your code refers to document instead of the input . 代码中的$(this)引用document而不是input

This fixes it: 可以解决此问题:

$(document).ready(function() {
  if ($('input[type=radio]').is(':checked')) {            
    $('input[type=radio]').parent('label').addClass('checked'); 
  }
});

You could also do it like this: 您也可以这样:

$(document).ready(function() {
  $('input[type=radio]:checked').parent('label').addClass('checked'); 
});

this in the following line refers to window 下一行中的this是指window

$(this).parent('label').addClass('checked');

You should do this instead: 您应该这样做:

$(document).ready(function() {
    var myInput = $('input[type=radio]');
    if (myInput.is(':checked')) {       
    myInput.parent('label').addClass('checked'); }      
});

Or, if you want to treat all the input on your page: 或者,如果您要处理页面上的所有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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM