将 child 的属性应用于 parent

Apply attribute of child to parent

我是 JS/jQuery 的新手,非常感谢您的帮助!:

对于每个具有 属性 属性的锚点,我需要获取其 child img 的 src 并将该值应用为parent 主播

例如:

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

谢谢!

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>

您可以执行以下代码 越短越好。

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

这将在锚点下的每个图像上循环并将其 src 值分配为其父锚点的 href 值

这应该可以完成工作,仅将 href 添加到具有 属性

的标签
  $("a").each(function (index, value) {
    if ($(this).attr("property")) {
      console.log($(this).children().attr("src"));
      $(this).attr("href", $(this).children().attr("src"));
    }
  });