2015-05-03 42 views
2

我是Javascript新手,我無法弄清楚如何在選定的選項上使用setAttribute。在選定的選項上使用setAttribute

我有一個選擇的元素在我的HTML使用id =僱員(使用JavaScript添加選項)現在

<select name="employee" id="employee"></select> 

,使用JavaScript(或jQuery的)我想一個「部門」屬性添加到選定動態選項。

但是,下面的代碼不起作用。我在這裏做錯了什麼?

var sel = document.getElementById("employee"); 
var selected = sel.options[sel.selectedIndex]; 
selected.setAttribute("data-dept", Support); 

我也試過:

$("#employee option:selected").setAttribute("data-dept", "Support"); 

這也沒有工作。你能幫我嗎?

回答

2

試試這個:

<!DOCTYPE html> 
<HTML> 
<HEAD> 
     <TITLE>Test</TITLE> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
</HEAD> 
<script> 
     $(document).ready(function() 
     { 
       function addOptions(selectId, list) 
       { 
         var i, l, opt, sel, name; 
         sel=document.getElementById(selectId); 
         sel.options.length=0; 
         for(i=0, l=list.length; i < l; i++) 
         { 
           opt=document.createElement('option'); 
           name=list[i].name; 
           opt.innerHTML=name; 
           opt.value=name; 
           opt.setAttribute("data-dept", list[i].dept); 
           sel.appendChild(opt); 
         } 
       } 

       function onEmplOptChange() 
       { 
         var empDept=$("#employee option:selected").attr('data-dept'); 
         $("#emp-dept").val(empDept); 
       } 

       function generateDept() 
       { 
         return "Support"; 
       } 

       function onGenBtnClk() 
       { 
         var newDept=generateDept(); 
         $("#employee option:selected").attr('data-dept', newDept); 
         $("#emp-dept").val(newDept); 
       } 

       function init() 
       { 
         var list=[{"name": "Chris", "dept": "no department"}, {"name": "Boris", "dept": "no department"}]; 
         addOptions("employee", list); 
         onEmplOptChange(); 
         $("#employee").change(onEmplOptChange); 
         $("#gen-dept").click(onGenBtnClk); 
       } 

       init(); 
     }); 
</script> 
<BODY class="textstyle"> 
     <div id="maindiv"> 
       <table> 
         <tr> 
           <td colspan="1" style="width: 80px; "> 
             <select name="employee" id="employee"></select> 
           </td> 
           <td colspan="1" style="width: 180px; "> 
             <input type="text" id="emp-dept" disabled="true"/> 
           </td> 
         </tr> 
       </table> 
       <hr> 
       <br> <input type="button" id="gen-dept" value="Generate Dept."/> 
</BODY> 
</HTML> 
+0

我想這運行它,但沒有工作.. :(.. 。其他建議? – Nik

+0

什麼是不工作? – Rayon

+0

這裏是一個示例.. http://jsfiddle.net/u6pbzwg5/ ..'克里斯'和'鮑里斯'都分配到'沒有部門'在開始。按照預期,我選擇'Chris'並點擊'Generate Dept'按鈕,我在文本輸入框中看到'支持'。但是,如果我改變僱用ee到'鮑里斯'並改變爲'克里斯',它仍然被設置爲'沒有部門'。我期待這是'支持',因爲selected.setAttribute(「data-dept」,newDept);命令。 – Nik

0

你的代碼是正確的,你只需要在更改事件jsfiddle

document.getElementById('employee').addEventListener('change', function() { 
    this.selectedOptions[0].setAttribute('data-dept', 'Employee'); 
}); 
相關問題