mouseleave not firing after mouseenter changes HTML within anchor

I'm sure I'm overlooking something but I can't seem to get the "mouseleave" event to fire after I replace the html within the anchor tag that triggered the mouseenter.

Adding code here but really it's much simpler if you visit the JSFiddle link below and hover over the star icons.

$(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>');

   });
});

Please see JSFiddle here. Simply hover over the star icons and you shall see what I mean.


The mouseleave event works when added

.star {
    display: block;
}

in CSS

Update: 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')
    });
});

Demo: https://jsfiddle.net/zbeyv6fo/


here is your solution try below code

$(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>');   
   });
});

Your fiddle here


I think that the reason why the mouse leave is not working is because the element which triggered the mouse enter event is removed from the DOM before it can trigger the mouseleave event.

you are replacing the html on mouse enter and the events are still delegated but the element is removed and is not the same element which triggered the mouseenter event so mouseleave is never fired!

链接地址: http://www.djcxy.com/p/25746.html

上一篇: NSNotificationCenter多次拨打电话

下一篇: mouseenter在锚点内改变HTML后不会触发