[英]How to get the html of an input checkbox with jquery or javascript?
This is what I have in html file 这就是我在HTML文件中
<label><input type="checkbox" id="abc-news-au" /> ABC News (AU)</label><br /> <label><input type="checkbox" id="ars-technica" /> Ars Technica</label><br /> <label><input type="checkbox" id="associated-press" /> Associated Press</label><br />
I want to get the text between labels Ex. 我想获取标签Ex之间的文本。 ABC NEWs (AU)
ABC新闻(澳大利亚)
I use the following code but didnt work *(v is the id of the element) 我使用下面的代码,但是没用*(v是元素的ID)
console.log("get text: "+ $("#"+v).text()) //(empty)
console.log("get text: "+ $("#"+v).html()) //undefined
The only code that shows something is 唯一显示某些内容的代码是
console.log("get text: "+ v) //abc-news-au
which is obviously the id of the element... How do I get the text of the element? 显然,这是元素的ID。如何获取元素的文本?
You can use $("#"+v).parent().text()
to get what you want. 您可以使用
$("#"+v).parent().text()
获得所需的内容。 This is because the text is inside <label>
node, not <input>
node. 这是因为文本在
<label>
节点内,而不是在<input>
节点内。
Example: https://jsfiddle.net/epL3tkza/ 示例: https : //jsfiddle.net/epL3tkza/
<input />
does not have any html()
or text()
. <input />
没有任何html()
或text()
。 It's a self closing tag. 这是一个自闭标签。 You want to get the
.text()
of it's wrapping <label>
. 您要获取包装
<label>
的.text()
。
Using jQuery
: 使用
jQuery
:
$('body').on('click','input', function(e){ console.log($(e.target).closest('label').text()); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label><input type="checkbox" id="abc-news-au" /> ABC News (AU)</label><br /> <label><input type="checkbox" id="ars-technica" /> Ars Technica</label><br /> <label><input type="checkbox" id="associated-press" /> Associated Press</label><br />
I want to get the text between labels Ex.
我想获取标签Ex之间的文本。 ABC NEWs (AU)
ABC新闻(澳大利亚)
you could use the DOM node nextSibling
property, example: 您可以使用DOM节点的
nextSibling
属性,例如:
<!DOCTYPE html> <html> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label><input type="checkbox" id="abc-news-au" /> ABC News (AU)</label><br /> <label><input type="checkbox" id="ars-technica" /> Ars Technica</label><br /> <label><input type="checkbox" id="associated-press" /> Associated Press</label><br /> <script> $('input[type=checkbox]').click(function (e) { if($(this).is(':checked')) { var data = this.nextSibling.nodeValue; console.log(data); } }); </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.