如何使用活动元素进行鼠标输入

How to mouseenter with live elements?

本文关键字:鼠标 输入 元素 何使用 活动      更新时间:2023-09-26

我在使用带有live元素的mouseenter时遇到问题。当我将鼠标悬停在添加了javascript的选定元素上时,这些函数不会被触发。

我添加了以下元素:

this.fixElements = function () {
    $('.iconstarsdynamic.isgradeable:not(.touched)').each(function(){
        var $self = $(this),
                $gradeLength = Math.round(parseInt($self.width())/$maxGrade*100)/100;
        $self.addClass('touched');
        for ($i = 1; $i <= $maxGrade; ++$i) {
            $('<span />', {
                "class" : "grader",
                "z-index" : $i,
                "width" : ($gradeLength*$i)+'px'
            }).attr('grade', $i).appendTo($self);
        }
    });
}

我试着用这个mouseenter

this.hover = function() {
    $('.iconstarsdynamic.isgradeable')
        .on('mouseenter', '.grader', function(){
            $(this).css('visibility', 'visible');
            console.log('over');
        })
        .on('mouseleave', '.grader', function(){
            $(this).css('visibility', 'hidden');
        });
}

我的输出如下:

<span class="iconstarsdynamic isgradeable touched" title="Rated 0 out of 4">
    <span class="stars" style="width:0%;"></span>
    <span class="grader" z-index="1" style="width: 9.25px; " grade="1"></span>
    <span class="grader" z-index="2" style="width: 18.5px; " grade="2"></span>
    <span class="grader" z-index="3" style="width: 27.75px; " grade="3"></span>
    <span class="grader" z-index="4" style="width: 37px; " grade="4"></span>
</span>

问题是mouseenter从不运行。为什么会这样?如果我将mouseenter附加到.iconstarsdynamic.isgradeable,它会起作用,但这不是我想要的。我想把它附在.iconstarsdynamic.isgradeable .grader上。

mouseentermouseleave事件不会冒泡,因此无法使用您使用的事件委派方法。您应该使用mouseovermouseout(如果有的话,您可能需要处理后代的事件)。