j查询如何为具有相同类名的多个元素激活一个事件

jQuery how to activate one event for multiple elements with same class name

本文关键字:激活 元素 事件 一个 查询 同类      更新时间:2023-09-26

我有多个具有不同 id 名称的div,如下所示:

<div id="person1">
    <img class="imgPerson" src="../images/person1.jpg">
    <div class="personBubble" style="display: none;">
        <div class="extraInfo">
            Sells carrots
        </div>
    </div>
</div>
<div id="person2">
    <img class="imgPerson" src="../images/person2.jpg">
    <div class="personBubble" style="display: none;">
        <div class="extraInfo">
            Sells onions
        </div>
    </div>
</div>
<div id="person3">
    <img class="imgPerson" src="../images/person3.jpg">
    <div class="personBubble" style="display: none;">
        <div class="extraInfo">
            Sells lettuce
        </div>
    </div>
</div>

如您所见,我有person1, person2, person3.我还有一个jQuery函数,当imgPerson悬停时,它为personBubble类设置display:block

$(".imgPerson").hover(
    function () {
        $(".personBubble").fadeIn(150);
    },
    function () {
        $(".personBubble").fadeOut(150);
});

但是,显然每个personBubble类都设置为在激活事件时display:block,因为它们都具有相同的名称。我只希望这种情况发生在相应的personBubble上,即如果 person1 的imgPerson处于悬停状态,则只有 person1 的personBubble应设置为 display: block

实现

这一点的最佳方法是什么,而不必为每个人使用唯一的 ID,而不必为每个 ID 编写相同的 jQuery 函数?

您可以引用指向当前上下文的 this 对象,并调用siblings()方法来搜索具有当前上下文.personBubble具有相应类名的同级。

$(".imgPerson").hover(
    function () {
       $(this).siblings(".personBubble").fadeIn(150);
    },
    function () {
       $(this).siblings(".personBubble").fadeOut(150);
   }
);

现场演示 @ JSFiddle

可以使用事件源对象$(this)来获取下一个personBubble

$(".imgPerson").hover(
    function () {
        $(this).next(".personBubble").fadeIn(150);
    },
    function () {
        $(this).next(".personBubble").fadeOut(150);
});

由于imgPersonpersonBubble是兄弟姐妹,您所要做的就是使用兄弟姐妹()

我建议你使用 fadeToggle() 它让你的代码更短,更短更好。

$(".imgPerson").hover(function(){
   $(this).siblings().fadeToggle(150);
});