Finding matched classname in jQuery

后端 未结 4 1713
执念已碎
执念已碎 2021-02-13 18:54

I have a series of image thumbnails in a page. They are created using css sprites.

4条回答
  •  执念已碎
    2021-02-13 19:36

    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.

    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!

提交回复
热议问题