使用jQuery选择器上的regex查找基于id的所有元素
我有几个具有唯一ID的元素,如下所示:
我希望以下内容可以使用jQuery:
$("#item-[.]+-top").each(function() { $(this).hide(); });
我没有很好地掌握正则表达式,我会很感激一些输入,因为上面看起来不正确。
如果您使用正则表达式执行此操作,表达式将只是:
item-\d-top
其中\d
表示任何单个数字(0..9),其他字符没有特殊含义(因此被视为文字)。
但是,jQuery目前没有正则表达式filter(只有start / end / contains / etc之类的东西) – 所以你必须自己创建一个(这是可能的,但如果你考虑到你应该停下来考虑一下/为什么你要过滤并弄清楚首先是否有更好的方法)。
更简单的是创建一个类(如serg555建议的那样) ,因为这正是你对待这些项目的方式。
或者(如果你不能改变标记来添加类)然后使用现有的filter,扩展gddc的答案 ,我可能会这样做:
$('div[id^=item-][id$=-top]').hide()
(由于您现在或将来可能有多个项目仅以’top’结尾,因此您需要更加具体,以避免无意中隐藏其他内容。)
如果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() ); });
我会像item
一样为它们分配一些类,然后通过这个类$(".item")
。
James Padolsey创建了一个很棒的filter ,允许使用正则表达式进行选择。
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)); }
现在你可以使用了
$('div:regex(id,item-[0-9]-top)').hide()
遇到类似的问题并喜欢/ upvoted serg的创建类的答案,但后来因为我对这些元素进行了多次操作, Keyed Collections更适合。