2017-01-30 33 views
1

屬性我有一個自定義屬性的選擇下拉菜單,看起來像這樣:如何通過選擇循環使用自定義jQuery的

<select id="myselect"> 
<option value="1" custattr="first">First One</option> 
<option value="2" custattr="second">Second One</option> 
<option value="3" custattr="third">Third One</option> 
</select> 

而且我有一個或多個值,我要再次進行測試,看看他們是否沒有出現在每個選項的custattr中。

我曾嘗試以下變化:

jQuery('#myselect option').attr('custattr').each(function(){ 
     if (myvalue != jQuery(this).attr('custattr').val()) { 
     //do something 
     } 
    }); 

,但我得到的錯誤,如:

Uncaught TypeError: Cannot read property 'each' of undefined

我怎麼能遍歷測試對每個custattr價值?

回答

1

你必須重複它像下面。

jQuery('#myselect option').each(function(){ 
    if (myvalue != jQuery(this).attr('custattr')) { 
    //do something 
}); 

.attr()將返回string。因此它的原始鏈中不會有一個稱爲each的功能。

+0

感謝我認爲這是答案的一部分,但是當我做出的改變現在我得到一個錯誤說'無法讀取的未定義的屬性「VAL」 ' – Stephen

+1

@Stephen,只要使用'如果(myvalue的!= jQuery的(本).attr( 'custattr'))'不需要'.VAL()' – Satpal

+0

哦咄!謝謝!一旦他們讓我接受答案。 – Stephen

0

如果你想獲取屬性ATTR「custattr」

//jquery 
$(document).on('change','select',function(){ 
    var attr= $(this).find('option:selected').attr('data-custattr'); 
    alert(attr) 
}); 
// JS 
document.querySelector('select').onchange = function(){ 
    var attr= this.selectedOptions[0].getAttribute('data-custattr'); 
    alert(attr); 
};