0

我正在为我的网站编写一个简单的灯箱脚本,该脚本将链接 (A) 包裹在图像周围。链接 URL 应该是图像的 SRC,但稍作操纵。

图片 URL 可能如下所示:“pb028855_copy_147x110.jpg”,我希望它从“copy ”之后到“.jpg”之前删除“147x110”。

我当前的脚本,将 SRC 从图像复制到链接是这样的:

$(function(){
    $('img.withCaption').each(function(){
        var $imgSrc = $(this).attr("src");
        $(this).wrap('<a rel="lightBox" />');
        $(this).parent().attr("href", ""+$imgSrc);
    });
});

如何使用属性的一部分?

先感谢您...

4

3 回答 3

1

如果您不确定数字究竟是什么,您可以使用带有正则表达式的replace()(docs)方法。

$(function(){
    $('img.withCaption').each(function(){
        var $imgSrc = this.src.replace(/_\d+x\d+\./,'.');
        $(this).wrap('<a rel="lightBox" />')
               .parent().attr("href", ""+$imgSrc);
    });
});

所以这:

pb028855_copy_147x110.jpg

最终会是这样:

pb028855_copy.jpg
于 2011-02-09T14:32:56.790 回答
0

它们是操作字符串的几种方法,取决于您到底想要什么,例如:

$imgSrc = $imgSrc.replace(/thumb/, 'big');
于 2011-02-09T14:32:40.890 回答
0

attr 方法只返回一个字符串,您可以像操作其他任何方法一样操作它。所以一个正则表达式替换会起作用。

$(function(){
    $('img.withCaption').each(function(){
        var imgSrc = $(this).attr("src")*.replace(/_copy_\d+x\d+\.jpg$/, "_copy.jpg")*;
        $(this).wrap($('<a rel="lightBox" />').attr("href", imgSrc);
    });
});

(我稍微清理了包装部分。)

于 2011-02-09T14:36:36.113 回答