[英]Get text node from checked radio button
这是一个当前选中的单选按钮的html:
<label>
<input type="radio" name="reason" value="1" data-promo="1">
"some text here bla bla"
</label>
有了我在这里找到的一行JS,我能够获取输入元素而不是文本:
document.querySelector('input[name="reason"]:checked');
返回:
<input type="radio" name="reason" value="1" data-promo="1">
我如何抓住这个元素后面的文字“这里有些文字bla bla”?
文本节点是复选框的下一个兄弟节点
function test() { var checkbox = document.querySelector('input[name="reason"]:checked'); if (checkbox) { var text = checkbox.nextSibling.textContent; alert(text); } }
<label> <input type="radio" name="reason" value="1" data-promo="1">text 1 </label> <label> <input type="radio" name="reason" value="2" data-promo="2">text 2 </label> <label> <input type="radio" name="reason" value="3" data-promo="3">text 3 </label> <label> <input type="radio" name="reason" value="4" data-promo="4">text 4 </label> <button onclick="test()">Test</button>
如果您事先不知道文本的位置,那么最简单的选项是访问父label
元素的textContent
属性 :
document.querySelector('input[name="reason"]:checked').parentElement.textContent;
当然,这假设它是label
元素中唯一的文本节点。
或者,如果文本总是出现在 input
元素之后,那么您可以只访问下一个兄弟的textContent
属性:
document.querySelector('input[name="reason"]:checked').nextSibling.textContent;
如果你想像你一样使用javascript,那么试试这个 -
alert(document.querySelector('input[name="reason"]:checked').nextSibling.textContent);
您也可以使用jQuery做这样的事情,
$('input[name="reason"]').on("click", function(){
alert($(this).closest("label").text());
});
我对你的代码做了一些小改动。 添加了data-txt
并使用了getAttribute
var a = document.querySelector('input[name="reason"]:checked').getAttribute("data-txt");
alert(a);
检查这对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.