首頁  >  文章  >  後端開發  >  js取得radio與select屬性的方法

js取得radio與select屬性的方法

WBOY
WBOY原創
2016-07-25 09:12:421408瀏覽

實現一個連動選單,目標: 1.點選“匿名小組”,自動跳轉:成員類型“私密群組”、存取控制 “群組成員” 2、點選“公開群”, 自動跳轉:成員類型“實名小組” 如下圖: js radio与select属性    首先,獲得點擊radio的事件,用的是jquery庫,獲得事件後判斷是那個radio,通過判斷是那個radio被checked了然後進行聯動變換。 其中遇到的問題有,相容ie和firefox的事件,然後設定select中的中options的selected屬性。

相容ie和firefox用了var ie=document.all;var nn6=document.getElementById&&!document.all; 設定select中的中options的selected屬性用的是var t=document.getElementsByName("select1")[0][1]; t.setAttribute("selected","selected"); 在設定selected屬性通常用的是document.getElementsByName("select1").options,但是firefox報undefined。於是遍歷後就用了一個陣列解決了。

例子,實現了目標1的完整程式碼:

  1. 實名小組(使用姓名)
  2. 匿名小組(使用暱稱)
  3. 公開群組
  4. 私密群
  5. // JavaScript Document
  6. var ie=document.all;
  7. var nn6=document.getElementById&&!document.all;
  8. $(document).ready(function(){
  9. $(":radio").click(function(e){
  10. var $name=(nn6?e.target.name:event.srcElement.name);
  11. if($name == " member_type")
  12. {
  13. if(1 == GetRadioValue($name))
  14. {
  15. SetRadioCheck("search_type",1);
  16. var t=document.getElementsByName("select1" )[0][1];
  17. t.setAttribute("selected","selected");
  18. }
  19. }
  20. });
  21. });
複製程式碼

實現目標2時,遇到了SetRadioCheck中的setAttribute不好使了,調試了也不知道什麼原因於是換了obj.checked = true; 實作功能1、2 js

  1. // JavaScript Document
  2. var ie=document.all;
  3. var nn6=document.getElementById&&!document.all; (document).ready(function(){
  4. /*點擊"匿名群組",自動跳轉:成員類型"私密群組"、存取控制"群組成員"*/
  5. $(":radio") .click(function(e){
  6. var $name=(nn6?e.target.name:event.srcElement.name);
  7. if($name == "member_type")
  8. {
  9. if(1 == GetRadioValue($name))
  10. {
  11. SetRadioCheck("search_type",1);
  12. var t=document.getElementsByName("select1")[0][1];
  13. t.setAttribute("selected","selected");
  14. }
  15. }
  16. /*點擊"公開群", 自動跳轉:成員類型"實名小組"*/
  17. if ($name == "search_type")
  18. {
  19. if(1 == GetRadioValue($name))
  20. {
  21. SetRadioCheck("member_type",0);
  22. }
  23. }
  24. });
  25. });
  26. /*取得被check的radio的值
  27. *RadioName:要取得radio值的radio群組名稱
  28. */
  29. function GetRadioValue( RadioName){
  30. var obj;
  31. obj=document.getElementsByName(RadioName);
  32. if(obj!=null){
  33. var i;
  34. for(i=0;iif(obj[i].checked){
  35. return obj[i].value;
  36. }
  37. }
  38. }
  39. return null;
  40. }
  41. /*設定被選取屬性
  42. *RadioName:要修改屬性radio群組的名稱
  43. *i:radio中第i個元素被選取
  44. */
  45. function SetRadioCheck(RadioName ,i){
  46. var obj;
  47. obj=document.getElementsByName(RadioName);
  48. //obj[i].setAttribute("checked","checked");
  49. obj[i] .checked = true;
  50. }
複製程式碼

對於在第二次呼叫SetRadioCheck

  1. if($name == "search_type")
  2. {
  3. if(1 == GetRadioValue($name))
  4. {
  5. SetRadioCheck("member_type",0);
  6. }
  7. }
  8. obj[i].setAttribute("checked","checked")的失效,也請指教。
複製程式碼


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn