开发者

Setting link href from child image src using jQuery

开发者 https://www.devze.com 2023-02-17 05:18 出处:网络
I am using .wrap() to create a link around each image within a certain <div>, and I need to set that link\'s href to be equal to that image\'s src value.

I am using .wrap() to create a link around each image within a certain <div>, and I need to set that link's href to be equal to that image's src value. I figured out how to do the selection and the substitution, but I can't figure out how to extract the src value.

This is the html structure:

<div class="divclass">
    <img src="path1" />
    <img src="path2" />
    <img src="path3" />
</div>

and the desired outcome is

<div class="divclass">
    <a class="linkclass" href="path1">
        <img src="path1" />
    </a>
    <a class="linkclass" href="path2">
        <img src="path2" />
    </a>
    <开发者_Python百科;a class="linkclass" href="path3">
        <img src="path3" />
    </a>
</div>

The easy part is creating the link around the images, and I use .wrap() to do so. Next I need to set the href value, and I can use .attr for that, but I don't know how to extract the value of src within the same call. This is what I have so far:

$('.divclass img').wrap("<a class=\"linkclass\" href="" />");
$('a.linkclass').attr("href", $(this).find('img').attr('src')); 

but this is not working. I suspect I'm using $(this) wrong, but can't figure out how/why.

Any help would be appreciated!


Try this and read through it. There are a few things that are worth knowing in these few lines. It is much like CephalidOne's solution but might be a bit easier to understand.

$('div.divclass img').each(function(){
    var $this = $(this);
    $this.wrap('<a href="' + $this.attr('src') + '"></a>');
});

See it work: http://jsfiddle.net/AAdWH/


$('.divclass img').wrap(function() {
  return '<a class="linkclass" href="' + $(this).attr('src') + '" />';
});


instead of :

$(this).find('img')

use:

$(this).children('img')

and your wrap is formatted incorrectly.

so in the end your code would be:

$('.divclass img').wrap("<a class='linkclass' />");
$('a.linkclass').attr("href", $(this).children('img').attr('src')); 

or change your code completely:

example (the fiddle):

$('.divclass').children('img')
    .each(function(){
        var $this = $(this)
        $this.wrap("<a class='linkclass'/>")
        $this.parent('.linkclass').attr("href", $this.attr('src')); 
     });
0

精彩评论

暂无评论...
验证码 换一张
取 消