【问题标题】:mouseleave not firing after mouseenter changes HTML within anchormouseenter 更改锚点内的 HTML 后 mouseleave 未触发
【发布时间】:2015-04-21 09:00:45
【问题描述】:

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

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

$(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只需将鼠标悬停在星形图标上,您就会明白我的意思。

【问题讨论】:

  • $(document) 可能是错误的选择器...您真的想在文档上跟踪 mouseleave 吗?为什么不使用星星?
  • 他在事件 '[id^=star-]' 之后声明选择器
  • 在重新定义 html 内容时使用前缀属性选择器 (id^=...) 而不是后缀选择器(例如 id$=-full)。
  • @JochenSchultz 我相信你读错了。 $(document).on('mouseenter', '[id^=star-]', function () 跟踪 ID 以 'star-' 开头的元素。
  • 应该是$('[id$=-full]')等等。

标签: javascript jquery mouseenter mouseleave


【解决方案1】:

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/

【讨论】:

  • 一句话:没有。请查看我更新的小提琴链接。您可以亲眼看到 mouseenter 工作正常。如果您注释掉 mouseenter,您可以看到 mouseleave 有效。如果你有两个,他们没有,不管“显示:块;”在 CSS 中。仍然感谢您的尝试。
  • @Adergaard 更新答案!
  • 太棒了!非常感谢。在每个函数中将 $(this) 更改为 $('a[id^=star-]') 也使其成为我正在寻找的行为。我接受了你的答案是正确的。非常感谢。
【解决方案2】:

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

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

【讨论】:

  • 我认为您的分析不适用:触发委托事件的锚元素不会被处理程序删除/添加,只有它们的内容是。
  • 感谢您的回答! mouseenter 触发我们通过 *ngIf 从 DOM 中删除的元素,现在它可以与 display: none 规则一起使用,就像一个魅力! :)
【解决方案3】:

这是您的解决方案,请尝试以下代码

$(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在这里

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 2019-07-14
    相关资源
    最近更新 更多