【问题标题】:How to find match selectors class and data attribute using jquery如何使用 jquery 查找匹配选择器类和数据属性
【发布时间】:2017-01-24 13:01:11
【问题描述】:

有没有办法同时匹配选择器类和数据属性?

查找匹配的下拉菜单,例如:

`<select class="type-featured" data-featured="normal">`
....
`<select class="type-featured" data-featured="classical">`
....
`<select class="type-featured" data-featured="modern">`

找到select,class等于type-featured AND data-featured value等于normal - 这里是代码:

$('.style-wrapper').each( function() {
    var $styles = $(this);
    if ( $styles.parents().find('select').is('.type-featured, [data-featured=normal]') ) {
    // do something here
    }
});

无论选择有type-featured 类还是data-featured="normal", data-featured="classical", data-featured="modern",我都得到了TRUE

如果匹配任何一个选择器,它似乎是 TRUE。

是否可以使用 .is 函数获得我想要的结果?可能正在使用匿名函数,例如:

.is( function() {
//here some logic to result
}); 

【问题讨论】:

    标签: javascript jquery jquery-selectors


    【解决方案1】:

    如果你部署了 jQuery:

    $('select.type-featured[data-featured="normal"]').each(function(){
    
        // [... DO SOMETHING...]
    
    });
    

    您将仅在具有以下特征的 &lt;select&gt; 元素上运行该函数:

    • class="type-featured"
    • data-featured="normal"

    【讨论】:

    • 我编写了这个示例代码。我的原始代码很大,很难解释。我可以解释得不好。好的,如果我们有select、input和textarea那怎么匹配呢?
    • 使用逗号,您可以指定任意数量的选择器组合成一个结果。请参阅:api.jquery.com/multiple-selector 例如 $('select.type-featured[data-featured="normal"], input.type-featured[data-featured="normal"], textarea.type-featured[data-featured="normal"]')
    【解决方案2】:

    尝试使用hasClass() 代替is(...) - 这将确定是否为任何匹配的元素分配了给定的类。

    【讨论】:

    • 如果将类分配给元素,.hasClass() 方法将返回 true。这是类和数据属性
    猜你喜欢
    • 2011-09-08
    • 2013-03-14
    • 2011-01-10
    • 1970-01-01
    • 2014-07-02
    • 2021-01-31
    • 1970-01-01
    • 2020-11-07
    相关资源
    最近更新 更多