如何为2个元素绑定相同的操作

Alo*_*lon 3 html javascript jquery

我有一个像这样的基本代码(重复多次):

<h3 class="header">The header</h3>
<div class="content"> The content 
    <div class="showUp">hidden text</div>
</div>
<h3 class="header">The header2</h3>
<div class="content"> The content 2
    <div class="showUp">hidden text 2</div>
</div>
Run Code Online (Sandbox Code Playgroud)

我想创建活动上一卷,如果我将鼠标悬停在h3 div.content.showup类将被显示.如果我滚动div.content课程,我只设法创建一个规则:

$('.content').mouseenter(function() {
    $(this).find(".showUp").animate({left: 0},300)
})
.mouseleave(function() {
    $(this).find(".showUp").animate({
        left: -200
    }, 500);
}); 
Run Code Online (Sandbox Code Playgroud)

我知道我可以像这样为标题创建一个事件:

$('h3').mouseenter(function() {
    $(this)**.next()**.find(".showUp")...
});
Run Code Online (Sandbox Code Playgroud)

但是我如何将这些元素绑定到元素上以使用单词"this"来执行相同的操作

Ale*_*olo 5

这应该可以解决问题.

$('.content, h3')
    .mouseenter(function() {
        $(this).find('+ .content > .showUp').add($(this).find('> .showUp')).stop().animate({left: 0},300)});
    })
    .mouseleave(function() {
        $(this).find('+ .content > .showUp').add($(this).find('> .showUp')).stop().animate({left: -200},500)});
    });
Run Code Online (Sandbox Code Playgroud)

我们把一个事件侦听器.contenth3.然后在事件监听器中,我们搜索一个直接兄弟,如果它存在(+ .content > .showUp)或直接子(> .showUp)(如果它存在).

所以,无论如何我们都会让.showUpdiv成为动画.

我还添加了.stop()在动画制作动画之前停止动画的方法(因此如果你将鼠标悬停在h3其后,它将不会有一些奇怪的行为.content.

我在这里做了一个基本的小提琴,所以你可以看到它是如何工作的.