<label for="radio1"> This Radio Button 1 has a label associated with it.</label> <input type="radio" name="Radio" id="radio1" />
上面的代碼有一個標籤和單選按鈕,該標籤與使用for屬性的單選按鈕關聯。使用javascript獲取關聯的單選按鈕標籤文本
如果用戶選擇/檢查相關的單選按鈕,我想獲得標籤文本。
<label for="radio1"> This Radio Button 1 has a label associated with it.</label> <input type="radio" name="Radio" id="radio1" />
上面的代碼有一個標籤和單選按鈕,該標籤與使用for屬性的單選按鈕關聯。使用javascript獲取關聯的單選按鈕標籤文本
如果用戶選擇/檢查相關的單選按鈕,我想獲得標籤文本。
如果您使用jQuery:
$('input[name="Radio"]').click(function(){ alert($(this).prev('label').text()) });
試試下面這個例子:http://jsfiddle.net/7FzQ9/
$('input#radio1').prev('label[for=radio1]').text();
$("input:radio").click(function() {
// if the label is before the radio button
alert($(this).prev("label").text());
// otherwise use
alert($("label[for='" + this.id + "']").text());
});
我知道這個問題是個老了,甚至已經有一個公認的答案,但每這裏的迴應使用prev
方法。只是想指出的是,一個稍微更強大的技術將使用屬性選擇:
$('input:radio').click(function() {
var txt = $('label[for=' + this.id + ']').text();
alert(txt);
});
您還可以使用:
$("input:radio").click(function() {
var label_description = this.parentElement.outerText;
alert(label_description);
})
的js小提琴測試: