创建更新的图像代码链接

时间:2018-03-22 19:27:02

标签: jquery

我正在尝试创建一个jquery代码,它可以使用链接包装img标记:

我的代码是这样的,

http://prntscr.com/iuw6hc

我会在这里粘贴我的html,但基本上它是在每个col

中显示的许多项目的循环
<div class="car-item gray-bg text-center first" style="height: 357px;">        
        <div class="car-image">            
            <img class="img-responsive" src="http:///wp-content/uploads/2018/03/20180214_090633-265x190.jpg" alt="" width="265" height="190">            
            <div class="car-overlay-banner">
                <ul>
                    <li><a href="http:///cars/chevrolet-silverado-1500-lt-z71/" data-toggle="tooltip" title="" data-original-title="View"><i class="fa fa-link"></i></a></li>

我正在尝试这样

var wrapped = false;
    var original = $(".img-responsive");

    $(".img-responsive").click(function(){
        if (!wrapped) {
            wrapped = true;
            var gURL = $('.car-overlay-banner').find('a').attr('href');
            $(".img-responsive").wrap("<a href=\"'+ gURL +'\"></a>");
        }
    });

    $(".img-responsive").click(function(){
        if (wrapped) {
            wrapped = false;
            $(".img-responsive").parent().replaceWith(original);
        }
    });

尝试使用汽车覆盖的href来应用于图像,

更新为代码:

$('.car-image img').each(function() { // For each image
    var ax = $(this).parents('div.car-image').find('a:first'); // Find its associated anchor 
    $(this).wrap('<a href="' + ax.attr('href') + '"></a>'); // And wrap the image
});

1 个答案:

答案 0 :(得分:1)

使用您要访问的href网址的数据属性制作html

            <img class="img-responsive" data-img-url="http:///cars/chevrolet-silverado-1500-lt-z71/" src="http:///wp-content/uploads/2018/03/20180214_090633-265x190.jpg" alt="" width="265" height="190">            

然后让你的jquery使用该url去那个位置:

$(".img-responsive").click(function(){
    var yourUrl = $(this).data('imgUrl');
    document.location.href = yourUrl;
});

当然,如果您可以在html设计时构建网址,那么您也可以将图像包装在html中的锚标记中。如果您不了解更多关于为什么要尝试使用javascript解决问题,那么这就是我为您所做的最好的事情。