Finding matched classname in jQuery

后端 未结 4 1712
执念已碎
执念已碎 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:20

    You could use a Regex, but using split and indexof will be understood by more programmers. Also for something so simple, maybe better to avoid Regex.

    In the event handler use the jQuery normalized Event object:

    $("[class^=galleryImg]").click(function(Event) {
        var classAttribute=Event.target.className
    
        var classes=classAttribute.split(" ");
    
        for (var i=0;i<classes.length;i++)
        {
            if (classes[i].indexOf('targetClassNamePrefix')==0)
            {
                // This element has the required class, do whatever you need to.
    
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-13 19:22

    What I do is something like this:

    <div class="galleryImg 1"></div>
    <div class="galleryImg 2 featured"></div>
    <div class="galleryImg 3"></div>
    
    <script>
    $(".galleryImg").click(function(Event) {
        var Class = $(this).attr('class').split(" ");
        var id = Class[1]
    });
    </script>
    
    0 讨论(0)
  • 2021-02-13 19:30

    Surprised nobody ever mentioned data attributes as a solution.

    More verbose and clearer and you can put whatever you want for the value.

    <div class="galleryImg1" data-imagename="cat" data-caption="This is a cat"></div>
    <div class="galleryImg2" data-imagename="img1"></div>
    

    With jQuery you can get the value with $(ele).data('imagename')

    0 讨论(0)
  • 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.

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

    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!

    0 讨论(0)
提交回复
热议问题