在jQuery选择器上使用正则表达式查找基于ID的所有元素 [英] Find all elements based on ids using regex on jQuery selector

查看:455
本文介绍了在jQuery选择器上使用正则表达式查找基于ID的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got several elements with unique ids like so:

<div id='item-1-top'></div>
<div id='item-2-top'></div>
<div id='item-3-top'></div>

我希望以下代码可以在jQuery中使用:

I was hoping that the following would work using jQuery:

$("#item-[.]+-top").each(function() {
  $(this).hide();
});

我对正则表达式没有很好的了解,请多多指教,因为上述内容似乎不正确.

I do not have a good grasp of regular expressions and I would appreciate some input, as the above appears to be incorrect.

推荐答案

如果使用正则表达式,则表达式将简单地是:

If you were doing this with regex, the expression would simply be:

item-\d-top

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

Where the \d indicates any single digit (0..9), and the other characters have no special meaning (so are treated as literals).

但是,jQuery当前没有正则表达式过滤器(仅包括start/end/contains/etc之类的东西)-因此您必须创建自己的正则表达式过滤器(可能的,但是如果您考虑停止然后考虑要过滤的内容/原因,并首先找出是否有更好的方法.

However, jQuery doesn't currently have a regex filter (only things like start/end/contains/etc) - so you would have to create your own one (which is possible, but if you were considering that you should stop and consider what/why you're filtering and figure out if there's a better way first).

更简单的方法是创建一个类(如

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()

(由于您可能现在或将来都有多个以"top"结尾的项目,因此您需要更加具体,以避免无意间隐藏其他内容.)

(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.)

这篇关于在jQuery选择器上使用正则表达式查找基于ID的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆