我是JSjQuery的新手,所以感谢任何帮助!
对于每个锚点,有 财产 属性,我需要获取它的子 img 的 src,并将该值作为父锚的 href。
所以,比如说。
<a property="1">
<img src="abc.jpg">
</a>
<a property="2">
<img src="def.jpg">
</a>
<a property="3">
<img src="ghi.jpg">
</a>
会变成:
<a href="abc.jpg" property="1">
<img src="abc.jpg">
</a>
<a href="def.jpg" property="2">
<img src="def.jpg">
</a>
<a href="ghi.jpg" property="1">
<img src="ghi.jpg">
</a>
谢谢你!
你可以用尽可能短的代码来完成下面的工作。
$('a>img').each(function(){
$(this).parent().attr('href',$(this).attr('src'))
});
这将在你的每个锚下的图片上循环,并将其src值作为父锚的href值。
document.querySelectorAll(img).forEach(el => {
el.parentNode.setAttribute('href', el.getAttribute('src'))
}
你可以这样做。
$("a").each(function() {
let href = $(this).find("img").attr("src");
$(this).attr("href", href);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a property="1">
<img src="abc.jpg">
</a>
<a property="2">
<img src="def.jpg">
</a>
<a property="3">
<img src="ghi.jpg">
</a>
这样做就可以了,只在有属性的标签上添加href值。
$("a").each(function (index, value) {
if ($(this).attr("property")) {
console.log($(this).children().attr("src"));
$(this).attr("href", $(this).children().attr("src"));
}
});