为重复元素触发mouseenter和mouseleave

Trigger mouseenter and mouseleave for repeating elements

本文关键字:mouseenter mouseleave 元素      更新时间:2023-09-26

我正在从MySql中获取数据,并将其显示在表中。我希望对于每个包含特定id<td>,使用jQuery在mouseenter上显示一些额外的信息,并在mouseleave上隐藏它。这是HTML输出:

<table>
    <tbody>
        <tr>
            <th>Option 1</th>
            <th>Option 2</th>
            <th>Option 3</th>
        </tr>
<?php   
    while ($row = mysqli_fetch_assoc($result)) {
?>  
    <tr>
        <td id="triggerTooltip"><?php echo $row['option1']; ?>
            <div class="tooltip">
                <p>Extra info</p>
            </div>
        </td>                   
        <td><?php echo $row['option2']; ?></td>
        <td><?php echo $row['option3']; ?></td>
    </tr>
<?php
    }
?>
    </tbody>
</table>

工具提示的默认display属性设置为none。这是我正在使用的jQuery:

$('#triggerTooltip').mouseenter(function() {
    $(this).closest('.tooltip').show();
}).mouseleave(function() {
    $(this).closest('.tooltip').hide();
});

我尝试过使用$(this).find('.tooltip'),它是有效的,但只是第一次出现#triggerTooltip。我想我弄错了。你能帮我弄清楚吗?非常感谢。

上面的答案是正确的,如果你愿意,这种行为也可以用CSS实现,规则如下:

.triggerTooltip .tooltip {
    display: none;
}
.triggerTooltip:hover .tooltip {
    display: block;
}

您似乎在复制(或复制)id。不要重复id!请改用类名。

$('.triggerTooltip').mouseenter(function() {
     $(this).find('.tooltip').show();  
}).mouseleave(function() {
     $(this).find('.tooltip').hide();
});

HTML

   <td class="triggerTooltip"><?php echo $row['option1']; ?>
        <div class="tooltip">
            <p>Extra info</p>
        </div>
    </td>             

尝试使用jquery hover,它将两个函数作为参数,并记住类和ID是不同的。ID在页面上是唯一的。

您可以使用:

$('#triggerTooltip').mouseenter(function() {
    $(this).find('.tooltip').each(function() {$(this).show()});
}).mouseleave(function() {
    $(this).find('.tooltip').each(function() {$(this).hide()});
});