简体   繁体   中英

before img add and close anchor tag using in jquery

I have the following code

<div id="slider">    
    <img src="images/p1.jpg" />
    <img src="images/p2.jpg" />
    <img src="images/p3.jpg" /> 
</div>

I want to add <a> before and after the image tag with jQuery. This would be the result:

<div id="slider">    
    <a href="http://www.google.com"><img src="images/p1.jpg" /></a>
    <a href="http://www.google.com"><img src="images/p2.jpg" /></a>
    <a href="http://www.google.com"><img src="images/p3.jpg" /></a>    
</div>

Edit: Details from comments

So far, I have tried like this:

<span class="phone"><img src="malsup.github.io/images/p1.jpg"></span>
<span class="phone"><img src="malsup.github.io/images/p2.jpg"></span>
<span class="phone"><img src="malsup.github.io/images/p3.jpg"></span>
<span class="phone"><img src="malsup.github.io/images/p4.jpg"></span>

i have add like

$('.phone').each(function() { 
    $(this).wrapInner('<a href="test.php" />'); 
});

Additional information from comments

I want to use a different url for each image, like:

<div id="slider">
  <a href="google.com"><img src="images/p1.jpg" /></a>
  <a href="yahoo.com"><img src="images/p2.jpg" /></a>
  <a href="facebook.com"><img src="images/p3.jpg" /></a>
</div> 

You can do it using the JQuery wrap() function like so:

var arr = ['https://www.google.com/', 'https://www.yahoo.com/', 'https://www.bing.com/'];

$("#slider img").each(function(index, value){
    $(this).wrap("<a href='"+arr[index]+"'></a>");
});

Here is the JSFiddle demo

Use .wrap()

Wrap an HTML structure around each element in the set of matched elements.

Here you can store different url in custom attributes which can later be used to wrap element.

 $('#slider img').wrap(function() { return $('<a />', { "href": $(this).data('url'), "class" : "myClass" }); }) 
 .myClass { border: 1px solid red } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="slider"> <img src="images/p1.jpg" data-url='facebook.com' /> <img src="images/p2.jpg" data-url='google.com' /> <img src="images/p3.jpg" data-url='example.com' /> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM