开发者

jQuery selecting with regular-expression and replacing links

开发者 https://www.devze.com 2023-02-21 17:35 出处:网络
I want to find all images inside some div an开发者_开发百科d replace the image tag with some other code. Replace this:

I want to find all images inside some div an开发者_开发百科d replace the image tag with some other code. Replace this:

<div id='sd'> <img src="/images/panorami/53.jpg"> <img src="/images/panorami/other.jpg"> </div>

with:

<div id='sd'> <a title="" rel="lightbox[images]" href="/images/panorami/53x.jpg"> <img src="/images/panorami/53.jpg"></a> <a title="" rel="lightbox[images]" href="/images/panorami/otherx.jpg"><img src="/images/panorami/other.jpg"></a> </div>

how this can be done with jQuery?


$('#sd img').wrap(function() {
    return $('<a />', {
        title: '',
        rel: 'lightbox[images]',
        href: this.src
    });
});

Demo.


Based on @jensgram answer, but with changed links like in question:

$(function() {
    $('#sd img').wrap(function() {
        fixed_url = $(this).attr('src').replace(/(\.[a-zA-Z]+)$/, 'x$1');
        return $('<a />', {
            title: '',
            rel: 'lightbox[images]',
            href: fixed_url
        });
    });
});

Example http://jsfiddle.net/sUsmA/1/

0

精彩评论

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