【发布时间】:2015-02-05 00:46:31
【问题描述】:
我有一个on 函数,其中有两个鼠标事件mouseenter 和mouseleave。当这些事件被触发时,它们会运行不同的函数,一个添加一个类,另一个删除它。
$(this).siblings('.testimonial').find('p').addClass('unseen');
$(this).siblings('.testimonial').find('p').removeClass('unseen');
问题是,我正在执行以下 DOM 遍历两次:
$(this).siblings('.testimonial').find('p')
但我不知道如何将这种遍历保存为一个函数中的变量并将其用作另一个函数。这是我的完整 JS 代码:
JavaScript
(function ($) {
var testimonial = $('.testimonial');
var testimonialHeight = testimonial.outerHeight();
var testimonialWidth = testimonial.outerWidth();
testimonial.find('p').addClass('unseen');
testimonial.css({
height: testimonialHeight,
width: testimonialWidth
});
$('.client').on({
mouseenter: function() {
$(this).siblings('.testimonial').find('p').removeClass('unseen');
},
mouseleave: function() {
$(this).siblings('.testimonial').find('p').addClass('unseen');
}
});
})(jQuery);
HTML
<ul class="list-unstyled list-inline">
<li>
<div class="testimonial"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.<p></div>
<img class="client" src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/128.jpg" alt="" />
</li>
<li>
<div class="testimonial"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p></div>
<img class="client" src="https://s3.amazonaws.com/uifaces/faces/twitter/gerrenlamson/128.jpg" alt="" />
</li>
<li>
<div class="testimonial"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p></div>
<img class="client" src="https://s3.amazonaws.com/uifaces/faces/twitter/jadlimcaco/128.jpg" alt="" />
</li>
</ul>
有人可以提出更好的方法吗?
谢谢。
【问题讨论】:
-
请向我们展示相关的 HTML,以便我们能够理解您所询问的 DOM 遍历以及您询问的哪一段代码?另外,您要解决的确切问题是什么?代码不起作用吗?还是您认为它太慢了?
-
当你可以做
.testimonial p时,你为什么要找到p?另外,您是否尝试过使用hover?为什么不在一个变量中进行遍历,然后向该变量添加/隐藏类...有点像您对testimonial所做的那样。 -
@jfriend00 我已经添加了上面的 HTML。代码有效,但问题是我在重复自己。我做了两次相同的 DOM 遍历。我希望代码能够工作,但我也希望它是 DRY。
-
@slime 因为当我使用
testimonial.find('p')时,我不会再次遍历整个 DOM。如果我使用$('.testimonial p'),那么我会的。我认为我在上面添加的 HTML 可能会让事情变得更清晰。 -
你说的是这段代码的两个副本:
$(this).siblings('.testimonial').find('p')?如果是这样,请在您的问题中这么说。您的许多代码都在进行 DOM 遍历,因此该短语本身并不能告诉我们您要询问的是哪一行代码。请努力使您的问题更加清楚。如果您要询问特定的代码行,请准确告诉我们是哪一行代码。
标签: javascript jquery dom traversal jquery-traversing