将子代的属性应用到父代

问题描述 投票:0回答:2

我是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>

谢谢你!

javascript jquery attributes jquery-selectors
2个回答
0
投票

你可以用尽可能短的代码来完成下面的工作。

$('a>img').each(function(){
    $(this).parent().attr('href',$(this).attr('src'))
});

这将在你的每个锚下的图片上循环,并将其src值作为父锚的href值。


0
投票
document.querySelectorAll(img).forEach(el => {
  el.parentNode.setAttribute('href', el.getAttribute('src'))
}

0
投票

你可以这样做。

$("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>

0
投票

这样做就可以了,只在有属性的标签上添加href值。

  $("a").each(function (index, value) {
    if ($(this).attr("property")) {
      console.log($(this).children().attr("src"));
      $(this).attr("href", $(this).children().attr("src"));
    }
  });
© www.soinside.com 2019 - 2024. All rights reserved.