不太确定如何在标题中添加该短语。无论如何,我的意思是我有三个具有相同类名的div。我想添加一个仅在选择div上起作用的鼠标悬停功能,而不是一次全部起作用。例如::(https://jsfiddle.net/1y2jw2y0/)这使所有div显示/隐藏,我只希望所选的div对jQuery函数起作用。

HTML:

<div class="box">
  <p class="show">Show</p>
  <p class="hide">hide</p>
</div>

<div class="box">
  <p class="show">Show</p>
  <p class="hide">hide</p>
</div>

<div class="box">
  <p class="show">Show</p>
  <p class="hide">hide</p>
</div>

CSS:
.box {
  display: inline-block;
  width: 150px;
  height: 150px;
  border: 1px solid #000;
}

.hide {
  display: none;
}

jQuery的:
$(document).ready(function() {
  $('.box').mouseover(function() {
    $('.hide').show();
    $('.show').hide();
  });
  $('.box').mouseleave(function() {
    $('.hide').hide();
    $('.show').show();
  });
});

最佳答案

使用this定位“selected”元素,然后使用 find() children() 选择子级:

$(document).ready(function() {
  $('.box').mouseover(function() {
    $(this).children('.hide').show();
    $(this).children('.show').hide();
  });
  $('.box').mouseleave(function() {
    $(this).children('.hide').hide();
    $(this).children('.show').show();
  });
});
JSFiddle Demo
编辑后,概述出现的性能问题:
有关findchildren之间的区别的基本详细信息,this answer是一个很好的资源。
在这种情况下,我发现.find()总体上更快,通常〜.2ms
经过大量测试后,看来使用find()或使用$('.selector', this)或使用$('.selector', this)和之间没有什么区别
总体而言,结果相似。在某些情况下,find()似乎更慢,而在其他情况下,find似乎更慢。
但是,$('.selector', this)确实为您提供了.selector > .anotherone无法实现的其他功能,例如直接子选择器:ojit_code,或缓存jQuery对象以节省资源。
简介:差别不大,这取决于您的情况以及您的喜好。

07-24 09:43
查看更多