jQuery 给定输入 ID,获取标签文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8470464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery given input ID, get label text
提问by delwin
In my HTML forms (as in most HTML forms), the labels share the same IDs as the fields. I'm trying to return to HTML of the label tag once the checkbox with a matching ID is clicked.
在我的 HTML 表单中(就像在大多数 HTML 表单中一样),标签与字段共享相同的 ID。单击具有匹配 ID 的复选框后,我将尝试返回标签标记的 HTML。
<input id="yes1" type="checkbox">
<label for="yes1">This is the text it should return.</label>
And my jQuery:
还有我的 jQuery:
$('input').change(function() {
if (this.checked) {
var response = $('label#' + $(this).attr('id')).html();
}
}
But alas, response comes out as NULL.
但可惜,响应结果为 NULL。
回答by AlienWebguy
$('input').change(function() {
if (this.checked) {
var response = $('label[for="' + this.id + '"]').html();
}
});
No need to get the id from the attribute.
无需从属性中获取 id。
回答by Murtaza
here is the basic example as per your requirement. You need the html content from the label next to your checkbox, if it is checked.
这是根据您的要求的基本示例。如果选中,您需要复选框旁边标签中的 html 内容。
use this
用这个
HTML
HTML
<div>
<form >
<input type="checkbox" id="yes" /><label for="yes">text yes </label>
<input type="checkbox" id="no" /><label for="no">text no</label>
</form>
</div>
JQUERY
查询
$('input').change(function() {
if (this.checked) {
var response = $(this).next("label").html();
alert(response);
}
})
回答by Jason
your syntax was a little wacked, try setting up the HTML like so
你的语法有点古怪,试着像这样设置 HTML
<input id="yes1" type="checkbox" />
<label for="yes1" id="yes1-label">This is the label</label>
and then use jquery like so
然后像这样使用jquery
$("#yes1").click(function() {
if ($("#yes1").is(":checked")) {
/* it's not really clear what you are trying to do here */
var response = $("#label").attr("id");
$("#yes1-label").text(response);
}
});