<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小提琴测试: