[英]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.