javascript - 如何在 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 必须设置在他的父属性上。
解决方案
您可以通过执行以下 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);
});
推荐阅读
- sql - 如何根据列值的优先级进行查询
- android - 找不到 `aapt` 命令,因此无法清理状态栏...
- google-sheets - COUNTIF 具有绝对列,Google 表格中的相对行
- java - 检索由 EMF 比较计算的 ADD Diff 中的“值匹配”
- powershell - 如何通过 Powershell 从 AD 组设置所有者属性(不由其管理)?
- javascript - 如何使用 jquery 从浏览器中的 Cookie 获取 sessionid?
- android - 使用 Glide 库:如何在头像右侧设置相机图标?
- android - 如何正确调用 newInstance 方法?
- arrays - discord.js 将 .json 值导入变量
- amazon-web-services - 在 AWS ECS 集群中将 Grafana 部署为 FARGATE 服务