简体   繁体   English

如何在jQuery或JavaScript中设置属性(基于子属性)?

[英]How can I set an attributes (base on child attributes) in jQuery or JavaScript?

I want to set an attribute on hover, based on his child attributes, by using jQuery. 我想使用jQuery根据其子属性设置悬停属性。 I have tried many ways to make this, but no luck. 我尝试了很多方法来实现这一目标,但是没有运气。 All attributes are same and not changing on hover. 所有属性都相同,并且悬停时不会更改。

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

What I want is when I hover on .menu-item I want to set .description 's img attribute on data-src attribute for each menu. 我想要的是当我将鼠标悬停在.menu-item我想在每个菜单的data-src属性上设置.description的img属性。 That means Attribute must set on his parent attribute. 这意味着必须在其父属性上设置Attribute。

You can achieve what you want by executing the following jQuery script: 您可以通过执行以下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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 jQuery 设置 @page CSS 属性? - How can I set @page CSS attributes with jQuery? 如何使用javascript或jQuery访问xml中的子元素属性? - How do I access sub-child attributes in xml using javascript or jQuery? 未将css属性设置为子元素。 jQuery的 - Not set css attributes to child elements. Jquery JavaScript:如何根据HTML代码中的数据属性设置JavaScript代码中的src? - JavaScript: How can I set src in the JavaScript code based on data attributes in the HTML code? 在JavaScript中,如何使用jQuery更新属性 - In JavaScript, how to update attributes with jQuery javascript / jquery如何设置多个属性 - javascript/jquery how to set more than one attributes 如何设置属于基类[继承]的子类对象的属性(属性)? (将Base的attr传递给Child) - How to set properties(attributes) of a Child class object which belong to Base Class [Inheritance]? (Pass Base's attr to Child) 我可以通过 Javascript 设置 HTML 视频属性吗? - Can I set HTML video attributes via Javascript? 我如何与子指令共享父指令上的属性 - how can i share attributes on a parent directive with a child directive 如何使用JavaScript或jQuery将样式表中CSS类的属性直接加载到哈希中? - How can I load the attributes of a CSS class in a stylesheet directly into a hash using JavaScript or jQuery?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM