如何在jQuery中的href之前显示图像src

问题描述 投票:1回答:2

有这个块:

jQuery(document).ready(function($) {
$("img[src$='.jpeg'], img[src$='.jpg'], img[src$='.png'], img[src$='.gif']").wrap('<div class="b-img"/>').each(function() {
        var src = $(this).attr('src');
        var a = $('<a/>').attr('href', src).addClass('img-link').colorbox();    
        $(this).wrap(a);
        });
})(jQuery);

之后有像<a href=""></a><img src>...这样的链接,但我需要在<img src>之前使用<a href="">

javascript jquery
2个回答
2
投票

您可以使用after()而不是wrap

jQuery(document).ready(function($) {
$("img[src$='.jpeg'], img[src$='.jpg'], img[src$='.png'], img[src$='.gif']").wrap('<div class="b-img"/>').each(function() {
        var src = $(this).attr('src');
        var a = $('<a/>').attr('href', src).addClass('img-link').colorbox();    
        $(this).after(a);
        });
})(jQuery);

根据OP的注释进行编辑,以更改图像src

jQuery(document).ready(function($) {
$("img[src$='.jpeg'], img[src$='.jpg'], img[src$='.png'], img[src$='.gif']").wrap('<div class="b-img"/>').each(function() {
        var src = $(this).attr('src');
        var a = $('<a/>').attr('href', src).addClass('img-link').colorbox();    
        $(this).after(a);
        $(this).attr('src', 'http://www.yoursite.com/images/img1.jpg');
        });
})(jQuery);

1
投票

insertBefore()this之前插入元素,如下所示:

$(function() {
   $("img").wrap('<div class="b-img"/>').each(function() {
     $('<a />', {href: this.src, 'class': 'img-link'}).colorbox().insertBefore(this);    
   });​
});​

此外,不需要检查所有可用的图像文件扩展名,如果您有svg等图像,请使用类。

© www.soinside.com 2019 - 2024. All rights reserved.