如何使用 jQuery 中的自定义属性遍历 select

how to loop through select with custom attributes in jQuery

我有一个 select 下拉菜单,其中包含如下所示的自定义属性:

<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 值?

你必须像下面这样迭代它。

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

.attr() 会 return 一个 string。因此它的原型链中不会有一个名为 each 的函数。

如果你想获得 属性 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);
};