mouseenter 在锚点内更改 HTML 后 mouseleave 未触发

mouseleave not firing after mouseenter changes HTML within anchor

我确定我忽略了一些东西,但在我替换触发 mouseenter 的锚标记内的 html 后,我似乎无法触发 "mouseleave" 事件。

在此处添加代码,但如果您访问下面的 JSFiddle link 并将鼠标悬停在星形图标上,实际上会简单得多。

$(document).ready(function () {
    $(document).on('mouseenter', '[id^=star-]', function () {

        $('[id^=star-]').html('<span class="star star-empty"></span>');

    }).on('mouseleave', '[id^=star-]', function () {

       $('[id^=star-]').html('<span class="star star-full"></span>');

   });
});

请参阅JSFiddle here只需将鼠标悬停在星形图标上,您就会明白我的意思。

添加后 mouseleave 事件有效

.star {
    display: block;
}

在CSS

更新: Javascript:

$(document).ready(function () {
    $('.rating').on('mouseenter', 'a[id^=star-]', function () {
        console.log('Hello');
        $(this).children('span').addClass('star-empty').removeClass('star-full');
    }).on('mouseleave', 'a[id^=star-]', function () {
        console.log('leave');
        $(this).children('span').addClass('star-full').removeClass('star-empty')
    });
});

演示:https://jsfiddle.net/zbeyv6fo/

这是您的解决方案尝试下面的代码

$(document).ready(function () {
    $(document).on('mouseenter', '.star-rating', function () {
console.log('as1s');
        $('[id^=star-]').html('<span class="star star-empty"></span>');

    }).on('mouseleave', '.star-rating', function () {
console.log('as');
        $('[id^=-full]').html('<span class="star star-full"></span>');
        $('[id^=-half]').html('<span class="star star-half"></span>');
        $('[id^=-empty]').html('<span class="star star-empty"></span>');   
   });
});

你的fiddle在这里

我认为鼠标离开不起作用的原因是触发鼠标进入事件的元素在触发鼠标离开事件之前从 DOM 中移除。

您正在替换鼠标输入时的 html,事件仍然被委托,但该元素已被删除并且与触发 mouseenter 事件的元素不同,因此永远不会触发 mouseleave!