简体   繁体   中英

Dynamically filling an anchor href using an img src with jquery

Basically I'm trying to grab the SRC of an image, wrap it in an anchor which then uses the SRC of the img as it's HREF, I've so far got the following code, but I'm a bit stuck as to how to finish it off, any ideas?

$('#detail img').wrap(function() {
return '<a href="" rel="one" class="fancybox" />';
  });

$('#detail img a').attr('src',$('#detail img').attr('src'));
$('#detail img').wrap(function() {
    return '<a href="' + this.src + '" rel="one" class="fancybox" />';
});

By the way, if you can modify initial HTML it's better then doing this with JS.

$('#detail img').wrap(function() {
    return '<a href="' + $(this).attr('src') + '" rel="one" class="fancybox" />';
});

Your second line would always use only the first img a found. Also, img a is not a valid selector anyway since a cannot be a child of img .

Inside the .wrap() function, this refers to the current element (the specific <img> ), so you could do this:

$('#detail img').wrap(function() {
    return '<a href="' + this.src + '" rel="one" class="fancybox" />';
});

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