如何在特定元素中选择 .not(this)



我创建了一个函数,当单击li元素时,该函数会淡入一些描述性信息。该函数淡化列表中的新信息。 不工作的线路$(".hover").not(".hover", this).fadeOut(200).removeClass("not-me");并理解它归结为.not(".hover", this).

我已经尝试过.not(this)但这无法正常工作。大概是因为它的this部分仍然是从 li 元素中选择的,最初是从 click 函数 $("ul li").click(function() { 中选择的。

有没有办法成功使用.not(".hover", this)

j查询:

$("ul li").click(function() {
  // Remove other divs with element currently shown
  $(".hover").not(".hover", this).fadeOut(200).removeClass("not-me");
  // Stop chosen element from fading out
  $(".hover", this).addClass("not-me").fadeIn(200);
});

.HTML:

<li>
  <div class="hover">
     <h3>Header</h3>
     <p>Shot but breif description, cut me off if you need to.</p>
   </div>
   <img src="/images/1.jpg" alt="" />
</li>
<li>
  <div class="hover">
     <h3>Header</h3>
     <p>Shot but breif description, cut me off if you need to.</p>
   </div>
   <img src="/images/2.jpg" alt="" />
</li>
<li>
  <div class="hover">
     <h3>Header</h3>
     <p>Shot but breif description, cut me off if you need to.</p>
   </div>
   <img src="/images/3.jpg" alt="" />
</li>

我想你正在寻找这个:

$("li").not(this).find(".hover");

这将为您提供所有.hover元素,不包括this的孩子。


您可能应该缓存该$('li')对象...

.not只接受一个参数。 此外,任何事情都不可能满足$(".hover").not(".hover"). 只需使用$(".hover").not(this)

http://api.jquery.com/not/

当您使用 .siblings() 时,这非常简单。从某种意义上说,它不会考虑当前<ul>之外的<li>

话虽如此,除非您稍后向页面添加更多列表,否则您的初始选择器$('ul li') ,除非您稍后向页面添加更多列表,则可能不合适。

$("ul li").click(function() {
  // Remove other divs with element currently shown
  $(this)
      .siblings() // get sibling li's
          .find('.hover') // and fadeout their inner .hover divs
              .fadeOut(200)
              .removeClass("not-me")
              .end()
          .end()
      .find('.hover')
          .fadeIn(200)
          .addClass("not-me")
});

最新更新