2014-03-30 103 views
0

問題很簡單,我發現了一些使用jquery的解決方案,但在本機JS中沒有找到答案。使用原生javascript從選擇中讀取數據屬性

無法讀取標籤的值,它應該在IE8工作+

var select = document.getElementById('test'); 

select.onchange = function() { 
    //Value works fine 
    //alert(select.options[0].value); 

    //How can I read data attribute? 
    alert(select.options[0].data-label); 
} 

HTML:

<select id="test"> 
    <option data-label="label-1" value="HK">Hong Kong</option> 
    <option data-label="label-2" value="CH">China</option> 
</select> 

http://jsfiddle.net/Lnybn/

回答

1

您可以使用getAttribute

像這樣:

alert(select.options[0].getAttribute('data-label')); 

演示:http://jsfiddle.net/Lnybn/1/

+0

感謝您的幫助! – RuntimeException

+0

@RuntimeException,實際上我不知道這一點。我不得不尋找答案,這就是爲什麼我第二次回答 –