[英]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.