开发者

Getting imagename and make link from <img> with jQuery

开发者 https://www.devze.com 2023-02-01 02:52 出处:网络
With jQuery, I want to make all images under a specific path on a site clickable and showing a big image using Fancybox, which is a lighbox variant plugin for jQuery.

With jQuery, I want to make all images under a specific path on a site clickable and showing a big image using Fancybox, which is a lighbox variant plugin for jQuery.

My small images are located under "images/products/small", the big ones under "images/products/big" and the imagename is always the same

The page is showing the image with the following code:

<img src="images/products/small/hat.jpg" alt="Nice hat">

What i want is some jQuery script that makes this into:

<a href="images/products/big/hat.jpg" class="fancybox"><img src="images/products/small/hat.jpg" alt="Nice hat"></a>
开发者_运维百科

Maybe the part with setting class on the link tag can be skipped and just activate fancybox on the element directly with $(elm).fancybox();

I was looking around a bit and it looks like the jQuery functions "attr" and "wrap" might be useful, but with my currently limited jQuery skills I can't really connect the dots.


You want to find all of the images, and then as you suspected, you can use wrap if you really want the structure to be modified:

$('some_parent_selector img[src*=/small]').wrap(function() {
    return "<a href='" + this.src.replace("/small", "/large") + "' class='fancybox'/>";
});

Live example (once you click the button, the elements will be wrapped; this may not be immediately obvious visually, but if you use Firebug or Dev Tools or even just click them...).

You were on the right track with attr, btw, but it happens that the src attribute is one of those that's reflected as a property on the HTMLImageElement DOM object, so you don't need to use attr.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号