在jQuery选择器上使用regex查找基于id的所有元素

Ste*_*eng 25 regex jquery jquery-selectors

我有几个具有唯一ID的元素,如下所示:

<div id='item-1-top'></div>
<div id='item-2-top'></div>
<div id='item-3-top'></div>
Run Code Online (Sandbox Code Playgroud)

我希望以下内容可以使用jQuery:

$("#item-[.]+-top").each(function() {
  $(this).hide();
});
Run Code Online (Sandbox Code Playgroud)

我对正则表达式没有很好的掌握,我会很感激一些输入,因为上面的内容似乎不正确.

Pet*_*ton 39

如果您使用正则表达式执行此操作,表达式将只是:

item-\d-top
Run Code Online (Sandbox Code Playgroud)

其中,\d表示任何单个数字(0..9),其他字符没有特殊含义(因此被视为文字).

但是,jQuery目前没有正则表达式过滤器(只有像start/end/contains/etc这样的东西) - 所以你必须创建自己的一个(这是可能的,但如果你考虑到你应该停下来考虑什么/为什么你要过滤并弄清楚是否有更好的方法).

Much simpler would be to create a class (as serg555 suggests), since that's exactly how you're treating these items.

Or (if you can't change the markup to add the class) then use the existing filters, expanding on g.d.d.c's answer, I might do:

$('div[id^=item-][id$=-top]').hide()
Run Code Online (Sandbox Code Playgroud)

(Since you may have multiple items ending with just 'top', either now or in future, so you need to be more specific to avoid unintentionally hiding other things.)


Har*_*K T 14

如果ID是像news-top-1,news-top-2,news-top-3,news-top-4等则选择会帮助你.

http://api.jquery.com/attribute-starts-with-selector/

$.each( $("input[name^='news-top-']"), function () {
  alert( $(this).hide() );
});
Run Code Online (Sandbox Code Playgroud)


ser*_*erg 8

我会给他们分配一些类item,然后通过这个类进行搜索$(".item").


vij*_*mar 5

James Padolsey 创建了一个很棒的过滤器,允许使用正则表达式进行选择。

jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ? 
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^s+|s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}
Run Code Online (Sandbox Code Playgroud)

现在你可以使用

$('div:regex(id,item-[0-9]-top)').hide()
Run Code Online (Sandbox Code Playgroud)