1. 程式人生 > >jQuery獲取radio選中後的文字

jQuery獲取radio選中後的文字

div text java 朋友 方法 dev 選中 type sdn

原文鏈接:http://blog.csdn.net/zhanyouwen/article/details/51393216

jQuery獲取radio選中後的文字
轉載 2016年05月13日 10:32:14 標簽:jQuery獲取radio選中後的文字 850
HTML 示例如下:


[html] view plain copy
<input type="radio" id="male" name="sex" value="1" />男 <input type="radio" id="female" name="sex" value="2" />女
在這裏直接給出 jQuery 獲取 radio 選中後的文本的方法,如下:

[html] view plain copy
$("input[name=‘sex‘]:checked")[0].nextSibling.nodeValue;
方法將 jQuery 對象轉換為 DOM 對象後,再使用原生的 javascript 方法獲取文本。在我回復朋友前,他通過在 radio 後添加 span 標記來解決這個問題:

[html] view plain copy
<input type="radio" id="male" name="sex" value="1" /><span>男</span>
接來下獲取時使用 next() 選擇器,如下:

[html] view plain copy
$("input[name=‘sex‘]:checked").next("span").text();
問題看似到這裏就結束了,其實不然,這並不是好的用戶體驗。好的做法應該為 radio 添加 for 標記,這樣在點擊 radio 文本"男"或"女"的時候也能選中 radio,這比讓用戶點擊一個小圓圈容易多了。所以最好的 HTML 標記應該如下:

[html] view plain copy
<input type="radio" id="male" name="sex" value="1" /> <label for="male">男</label> <input type="radio" id="female" name="sex" value="2" /> <label for="female">女</label>
最後獲取 radio 選中後的文本我相信你已經會了,如下:

[html] view plain copy
$("input[name=‘sex‘]:checked").next("label").text();
這樣使用 jQuery 成功獲取了 radio 選中後的文本,這裏主要是指最後一個方法。本篇內容雖然簡單,但著重說明了一個道理——細節決定成敗!

jQuery獲取radio選中後的文字