在jQuery中查找匹配的类名 [英] Finding matched classname in jQuery
问题描述
我在页面中有一系列图像缩略图.它们是使用CSS精灵创建的.
I have a series of image thumbnails in a page. They are created using css sprites.
<div class="galleryImg1"></div>
<div class="galleryImg2 featured"></div>
<div class="galleryImg3"></div>
我最初使用的是id="galleryImg1"
,但后来改为使用class="galleryImg1"
,因为图像可能会出现在同一页面的多个位置,并且我想避免重复的ID.
I was originally using id="galleryImg1"
but changed to using class="galleryImg1"
because the images may appear in multiple places on the same page and i wanted to avoid duplicate ids.
我有一个jQuery选择器,将点击事件附加到所有这些类上.
I have a jQuery selector to attach click events to all of these classes.
$("[class^=galleryImg]").click(function() {
// how do i get 'galleryImg2' and '2' here?
}
我想知道的是,是否有一种简单的方法可以找到以'galleryImg'开头的className.我需要使用正则表达式还是聪明的"方式?
What I'm wondering is if there is an easy way to find out the className beginning with 'galleryImg' that was clicked on. Will I have to use a regular expression or is there a 'cleverer' way?
(是的,如果我使用的是#ID选择器,那么我只能说'this.id',但是如上所述,我不想使用ID,因为我想显示同一图像的多个副本.)
(yes if i was using an #ID selector then I could just say 'this.id' but as mentioned I don't want to use IDs because I want to display multiple copies of the same image.)
推荐答案
据我所知,您将需要一个非常基本的正则表达式,如下所示:
As far as I know, you're going to need a pretty basic regular expression, like so:
$("[class^=galleryImg]").click(function(Event) {
var id = this.className.match(/galleryImg(\d+)/)[1];
console.log(id);
});
但是,如果您特别反对这一点,则可以使用类似的方法,该方法将不会生效,但可以完成任务.
If you're particularly averse to this, though, you can use something like this, which won't validate but will Get The Job Done.
<div class="galleryImg1" image_id="1"></div>
<div class="galleryImg2 featured" image_id="2"></div>
<div class="galleryImg3" image_id="3"></div>
<script>
$("[class^=galleryImg]").click(function(Event) {
var id = $(this).attr('image_id');
console.log(id);
});
</script>
由于我假设您对HTML拥有完全控制权,并且您知道galleryImg类将始终带有ID,因此我认为此处的正则表达式根本不是邪恶的.随它去吧!
Since I am assuming you have full control over your HTML and you know that galleryImg class will always be followed by the ID I don't think a regular expression here is evil at all. Just go with it!
这篇关于在jQuery中查找匹配的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!