使用jQuery从子图像src设置链接href [英] Setting link href from child image src using jQuery

查看:126
本文介绍了使用jQuery从子图像src设置链接href的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.wrap()在某个<div>内的每个图像周围创建链接,我需要将该链接的href设置为等于该图像的src值. 我想出了如何进行选择和替换的方法,但我想不出如何提取src值.

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.

这是html结构:

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

期望的结果是

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

最简单的部分是在图像周围创建链接,而我使用.wrap()来做到这一点. 接下来,我需要设置href值,并且可以使用.attr,但是我不知道如何在同一调用中提取src的值.这是我到目前为止的内容:

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')); 

但是这不起作用.我怀疑我在$(this)上使用错误,但无法弄清楚如何/为什么.

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

任何帮助将不胜感激!

推荐答案

尝试一下并通读它.在这几行中,有几件事是值得了解的.它与CephalidOne的解决方案非常相似,但可能更容易理解.

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>');
});

查看其工作原理: http://jsfiddle.net/AAdWH/

这篇关于使用jQuery从子图像src设置链接href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆