开发者

Wrapping images with <a> jQuery problem

HI all,

I have a bunch of images that I need to wrap in a tag and add to a tag ref from image '+big' plus use image lint as a title for link.

The problems I have here are, 1) Images are wrapping with this same href from first image and title attribute is not showing.

This is my jQuery

$(document).ready(function(){
        var ImgLink = $('.gallery img');

        var ImgTitle = ImgLink.attr('src');

        var ImgDes = ImgLink.attr('alt'开发者_如何转开发)

        ImgLink.each(function(){
                              $(this).wrap($('<a></a>')
                                            .attr('href', ImgTitle.replace(/\./, 'big.'), 'title'.ImgDes)
                                            )})

})

This is my HTML

<img  alt="some alt" src="1.jpg"/></a>
<img  alt="some other alt" src="2.jpg"/></a>
<img  alt="and another alt" src="3jpg"/></a>

And this is the result

<a href="1big.jpg"><img  alt="some alt" src="1.jpg"/></a>
<a href="1big.jpg"><img  alt="some other alt" src="2.jpg"/></a>
<a href="1big.jpg"><img  alt="and another alt" src="3.jpg"/></a>

Thank you for your help in advance


You need to iterate over the images and perform the action of creating the <a> with each, as you need the src that is specific to the image in each case. Assuming that your image file anmes are in the format specified in the question

$('img').each(function() {
    var $this = $(this);
    var href = this.src.replace(/\./, "big.");
    var title = $this.attr('alt');
    $this.wrap('<a href="' + href + '" title="' + title + '"></a>');
});

Or using your original code,

$(document).ready(function(){
        var ImgLink = $('.gallery img');

        ImgLink.each(function(){
            var $this = $(this);
            var ImgTitle = $this.attr('src');
            var ImgDes = $this.attr('alt');
            var anchor = $('<a href="' + ImgTitle.replace(/\./, "big.") + '" title="' + ImgDes + '"></a>');
            $this.wrap(anchor);
        });
})
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜