简体   繁体   English

选择大孩子元素

[英]select grand children elements

I'm struggling to select my img Element in a list so i can switch its class on and off. 我正在努力在列表中选择我的img元素,因此我可以打开和关闭其类。 I've tried different way to select it but its the first picture of my list that lights up, even when mouseover on the second/third/... div of the list. 我尝试了不同的方法来选择它,但是即使将鼠标悬停在列表的第二/第三/ ... div上,它的列表中的第一张图片也会亮起。

<ul>
  <li>
    <div class="container" onmouseover="toggleImgColor()" onmouseout="toggleImgColor()">
      <div class="container-title">
        <h3 class="title />
        <img id="pic" class="greyImg" />
      </div>
      ...
    </div>
  </li>
  ...
</ul>

Javascript Java脚本

function toggleImgColor() {
  $(this).find("img").toggleClass("greyImg");
}

You can do that something like this: 您可以执行以下操作:

$(document).ready(function(){
   $(".container").hover(function() {
      $("#pic").toggleClass("greyImg");
   });
});

Just pass this inside the toggleImgColor() in html like toggleImgColor(this) , and catch that as parameter in javascript function. 只是通过this内部toggleImgColor()在HTML像toggleImgColor(this) ,并赶上在javascript函数的参数。 This will pass current hovered DOM object to toggleImgColor function and you can then use that to show that specific div. 这会将当前悬停的DOM对象传递给toggleImgColor函数,然后您可以使用该对象显示特定的div。

HTML: HTML:

<ul>
  <li>
    <div class="container" onmouseover="toggleImgColor(this)" onmouseout="toggleImgColor(this)">
      <div class="container-title">
        <h3 class="title />
        <img class="greyImg" />
      </div>
      ...
    </div>
  </li>
  ...
</ul>

JavaScript: JavaScript:

function toggleImgColor(item) {
  $(item).find("img").toggleClass("greyImg");
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM