首页 > 解决方案 > 如何在 jQuery 或 JavaScript 中设置属性(基于子属性)?

问题描述

我想使用 jQuery 根据他的子属性在悬停时设置一个属性。我尝试了很多方法来做到这一点,但没有运气。所有属性都是相同的,并且在悬停时不会改变。

<li class="menu-item">
  <a data-src="" class="menu-item-link" href="#">Item one</a>
  <span class="description">
    <img  src="https://i.ibb.co/LxSKFgH/image1.jpg">
  </span>
</li>

<li class="menu-item">
  <a data-src="" class="menu-item-link" href="#">Item two</a>
  <span class="description">
    <img src="https://i.ibb.co/TLJL7hq/image2.jpg">
  </span>
</li>

我想要的是当我将鼠标悬停在.menu-item我想为每个菜单.description的属性上设置 img 属性时。data-src这意味着 Attribute 必须设置在他的父属性上。

标签: javascriptjqueryhtml

解决方案


您可以通过执行以下 jQuery 脚本来实现您想要的:

$(".menu-item").hover(function(){
   //Take the src value from the inner img tag
   let srcValue = ($(this).find("img").attr("src"));
   //Set the data-src attribute of the inner anchor tag
   $(this).find("a").attr("data-src", srcValue);
});

推荐阅读