jQuery选择正则表达式并替换链接

时间:2011-03-31 10:57:14

标签: jquery regex

我想在某个div中找到所有图像,并用其他代码替换图像标记。替换这个:

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

使用:

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

如何使用jQuery完成此操作?

2 个答案:

答案 0 :(得分:4)

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

Demo

答案 1 :(得分:1)

基于@jensgram的答案,但改变了链接,如问题:

$(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
        });
    });
});

示例http://jsfiddle.net/sUsmA/1/

相关问题