[英]Insert anchor tag before image tag jQuery
I am trying to make image clickable and for this I want to wrap image within anchor tag, following is the code I tried but its generating anchor tag after image tag 我正在尝试使图像可点击,为此,我想将图像包装在锚标记中,以下是我尝试过的代码,但是它在图像标记之后生成了锚标记
This is the HTML code 这是HTML代码
jQuery(document).ready(function($){ jQuery('.fancybox-inner').append('<a href="#" class="new-img-holder"></a>'); jQuery('.fancybox-image').appendTo('new-img-holder'); });
<div class="fancybox-outer"> <div class="fancybox-inner" style="overflow: visible; width: 640px; height: 463px;"> <img class="fancybox-image" src="cine-sudarshan.jpg" alt=""> </div> </div>
Get the HTML inside the container, add the anchor tag and append it again. 在容器内获取HTML,添加定位标记并再次添加。
jQuery(document).ready(function($) { var html = jQuery('.fancybox-inner').html() var newHtml = '<a href="#" class="new-img-holder">' + html + '</a>' jQuery('.fancybox-outer').empty().html(newHtml); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="fancybox-outer"> <div class="fancybox-inner" style="overflow: visible; width: 640px; height: 463px;"> <img class="fancybox-image" src="cine-sudarshan.jpg" alt=""> </div> </div>
我将为此使用jQuery .wrap()
函数。
$( ".fancybox-image" ).wrap( "<a href='LINK_TO_NAVIGATE'></a>" );
If you just want the anchor to go before , use jQuery's .prepend
or .prependTo
methods. 如果您只是想让锚
.prepend
在前面 ,请使用jQuery的.prepend
或.prependTo
方法。 If you want to truly wrap it, then use jQuery's .wrap
method. 如果要真正包装它,请使用jQuery的
.wrap
方法。
(Or, perhaps the more correct answer is Sytor's -- which is to just do it directly in your markup.) (或者,也许更正确的答案是Sytor的答案-就是直接在您的标记中这样做。)
$(".fancybox-image").wrap('<a href="#" class="new-img-holder"></a>');
Try below code. 尝试下面的代码。 It's easy if you use jquery wrap function.
如果使用jquery wrap函数,这很容易。
jQuery(document).ready(function ($) { $(".fancybox-image").wrap('<a href="javascript:void(0)" onclick="alert(\\'clicked anchor tag\\')" class="new-img-holder"></a>'); //jQuery('.fancybox-inner').wrap('<a href="#" class="new-img-holder"></a>'); //jQuery('.fancybox-image').wrap('new-img-holder'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="fancybox-outer"> <div class="fancybox-inner" style="overflow: visible; width: 640px; height: 463px;"> <img class="fancybox-image" src="http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/sample1_l.jpg" alt=""> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.