jQuery獲取radio選中后的文字


原文鏈接: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 選中后的文本,這里主要是指最后一個方法。本篇內容雖然簡單,但着重說明了一個道理——細節決定成敗!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM