2013-07-24 20 views
0

http://jsfiddle.net/Yuxfv/2/在標籤上單擊返回其無線電組名

我希望能夠點擊的標籤上,看看它所屬的單選按鈕組。我試過這個,但它總是找到li(name = left)之後的第一個輸入,而不是最接近標籤的那個。我如何解決這個問題?

$('input[type=radio]:enabled + label').click(function() { 
    var thisGroupName = $(this).closest('ul').find('input[type=radio]:enabled').attr('name'); 
    alert("group name: " + thisGroupName); 
}); 

HTML

<ul> 
    <li> 
     <input type="radio" class="radio-red" name="left" id="a1"> 
     <label for="a1">a1</label> 
     <input type="radio" class="radio-blue" name="right" id="a2"> 
     <label for="a2">a2</label> 
    </li> 
    <li> 
     <input type="radio" class="radio-red" name="left" id="b1"> 
     <label for="b1">b1</label> 
     <input type="radio" class="radio-blue" name="right" id="b2"> 
     <label for="b2">b2</label> 
    </li> 
    <li> 
     <input type="radio" class="radio-red" name="left" id="b3"> 
     <label for="b3">b3</label> 
     <input type="radio" class="radio-blue" name="right" id="b4"> 
     <label for="b4">b4</label> 
    </li> 
</ul> 
+0

您是否試圖獲得標籤製作的單選按鈕的名稱? – Ahmad

+0

http://jsfiddle.net/Yuxfv/3/ – arma

+0

@Ahmad,yes.prev()解決了它。 – tuco

回答

2

不要去ul回來到li。嘗試使用prev(),如果你需要得到input的組:

$('input[type=radio]:enabled + label').click(function() { 
    var thisGroupName = $(this).prev('input[type=radio]:checked').attr('name'); 
    alert("group name: " + thisGroupName); 
}); 

要獲得更具體,你有for屬性與您聯繫。爲什麼不使用它?

$('input[type=radio]:enabled + label').click(function() { 
     var thisGroupName = $("#" + $(this).attr("for")).attr('name'); 
     alert("group name: " + thisGroupName); 
}); 
0

在你提供你也可以查找的單選按鈕明確使用點擊標籤「的」屬性的代碼示例。

$(document).ready(function() { 
    $('input[type=radio]:enabled + label').click(function() { 
     var forName = $(this).attr('for'); 
     var thisGroupName = $('#' + forName).attr('name'); 
      alert("group name: " + thisGroupName); 
    }); 
}); 

它是工作在此的jsfiddle: http://jsfiddle.net/Yuxfv/4/

1

我認爲你需要這樣的:

$('label').click(function(){ 
var forRadio = $(this).attr('for'); 
var groupName = $('#'+forRadio).attr('name'); 
alert(groupName); 

});

我做了這裏的jsfiddle http://jsfiddle.net/psmkw/

0

存在以這種方式遍歷DOM沒有意義,標籤必須元素的引用。點擊標籤時用於點擊它。

$('input[type=radio]:enabled + label').click(function() { 
    var input_id = '#'+$(this).attr('for'); 
    var group_name = $(input_id).attr('name'); 
    alert("group name: " + group_name); 
});