开发者

Manipulating a copied attr

I'm working on a simple lightbox script for my website, that wraps a link (A) around a image. The link URL should then be the SRC of the image, but slightly manipulated.

The image URL could look like this: "pb028855_copy_147x110.jpg" and I want it to delete "147x110", from after "copy" to befor开发者_运维问答e ".jpg" that is.

My current script, to copy the SRC from the image to the link is like this:

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

How can I use parts of a attr?

Thank you in advance...


If you're not certain exactly what the numbers will be, you could use the replace()(docs) method with a regular expression.

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

So this:

pb028855_copy_147x110.jpg

will end up as this:

pb028855_copy.jpg


They are several ways of manipulating strings, depends of what you exactly want, for example:

$imgSrc = $imgSrc.replace(/thumb/, 'big');


The attr method simply returns a string, you can manipulate it just like any other one. So a regex replace would work.

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

(I cleaned up the wrapping part a bit.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜