[英]Adding class to next element using jquery
I am having html like this: 我有这样的html:
<form>
<div class="row">
<input type="radio" class="radio">
<label>Text</label>
<input type="radio" class="radio">
<label>Type</label>
</div>
</form>
Now I need to apply a class to each label immediate after each <input type="radio">
. 现在,我需要在每个
<input type="radio">
之后的每个标签上立即应用一个类。
I am using jquery like this: 我正在使用像这样的jQuery:
if($('input').hasClass('radio')){
$(this).next().addClass('radio-url');
}
I am trying to add class 'radio-url' to each <label>
immediately after radio tag. 我试图在单选标记后立即向每个
<label>
添加类'radio-url'。 What mistake have I did in this? 我在这方面犯了什么错误?
You can use .siblings() 您可以使用.siblings()
$('input[type="radio"]').siblings('label').addClass('radio-url');
Or 要么
$('input[type="radio"]').next('label').addClass('radio-url');
Try: 尝试:
$(':radio').next().addClass('radio-url');
jsFiddle example (I threw a text input in there so you can see that it works on only radio inputs) jsFiddle示例 (我在其中输入了文本输入,因此您可以看到它仅适用于单选输入)
您可以使用next()函数
$("input:radio").next('label').addClass("radio-url");`
This answer doesn't directly answer your question! 这个答案不会直接回答您的问题!
I believe that your label should have the for attribute so that the label is associated with the radio button. 我认为您的标签应具有for属性,以便该标签与单选按钮关联。 This allows the user:
这允许用户:
HTML HTML
<div class="row">
<input type="radio" class="radio" id="text"></input>
<label for="text">Text</label>
<input type="radio" class="radio" id="type"></input>
<label for="type">Type</label>
</div>
JQuery JQuery的
Search the label using the radio element's ID. 使用单选元素的ID搜索标签。
$('input[type="radio"]').each(function(){
var radioId = $(this).attr("id");
$("label[for='" + radioId + "']").addClass('radio-url');
});
Fiddle: http://jsfiddle.net/78zAB/ 小提琴: http : //jsfiddle.net/78zAB/
You need to loop through all radio buttons: 您需要遍历所有单选按钮:
$('input[type="radio"]').each(function(){
$(this).next().addClass('radio-url');
});
Or 要么
$("input[type='radio'] + label").addClass('radio-url')
Use CSS element+element selector: 使用CSS元素+元素选择器:
$('input:radio + label').addClass('theClass')
Works optimal 效果最佳
$('input[type=radio]').next('label').addClass('radio-url');
Posting this as an answer as all of the others are using the incorrect selector, or don't specify the label
in next()
: 将其作为答案发布,因为其他所有其他人都使用了错误的选择器,或者没有在
next()
指定label
:
$('input.radio').next('label').addClass('radio-url');
.. which will add the class radio-url
to all label
elements which come immediately after an input
with the class radio
..会将
radio-url
类添加到在input
radio
类之后立即出现的所有label
元素中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.