[英]Adding class to next element using jquery
我有这样的html:
<form>
<div class="row">
<input type="radio" class="radio">
<label>Text</label>
<input type="radio" class="radio">
<label>Type</label>
</div>
</form>
现在,我需要在每个<input type="radio">
之后的每个标签上立即应用一个类。
我正在使用像这样的jQuery:
if($('input').hasClass('radio')){
$(this).next().addClass('radio-url');
}
我试图在单选标记后立即向每个<label>
添加类'radio-url'。 我在这方面犯了什么错误?
您可以使用.siblings()
$('input[type="radio"]').siblings('label').addClass('radio-url');
要么
$('input[type="radio"]').next('label').addClass('radio-url');
您可以使用next()函数
$("input:radio").next('label').addClass("radio-url");`
这个答案不会直接回答您的问题!
我认为您的标签应具有for属性,以便该标签与单选按钮关联。 这允许用户:
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的
使用单选元素的ID搜索标签。
$('input[type="radio"]').each(function(){
var radioId = $(this).attr("id");
$("label[for='" + radioId + "']").addClass('radio-url');
});
小提琴: http : //jsfiddle.net/78zAB/
$('input.radio').each(function () {
$(this).next().addClass('radio-url');
})
将其作为答案发布,因为其他所有其他人都使用了错误的选择器,或者没有在next()
指定label
:
$('input.radio').next('label').addClass('radio-url');
..会将radio-url
类添加到在input
radio
类之后立即出现的所有label
元素中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.