【问题标题】:how to loop through select with custom attributes in jQuery如何在jQuery中使用自定义属性循环选择
【发布时间】:2017-06-15 17:34:05
【问题描述】:

我有一个带有如下自定义属性的选择下拉菜单:

<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
       }
    });

但我收到如下错误:

未捕获的类型错误:无法读取未定义的属性“每个”

如何循环测试每个 custattr 值?

【问题讨论】:

    标签: jquery each attr


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,我认为这是答案的一部分,但是当我进行更改时,我现在收到错误消息 Cannot read property 'val' of undefined
    • @Stephen,只需使用if(myvalue != jQuery(this).attr('custattr')) 不需要.val()
    • 哦,呵呵!谢谢!只要他们让我接受就作为答案。
    • @Satpal 谢谢伙计。我发完这个就出去了。没注意到。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 2010-09-10
      • 1970-01-01
      • 2013-08-20
      • 2022-01-17
      • 1970-01-01
      • 2011-05-07
      相关资源
      最近更新 更多