问题
Both of these .hover(function() {...}, function() {...})
using either the element ID or this
work:
$( "#imgPostTravel" ).hover(function() {
$('#imgPostTravel').addClass('popout_image');
$('#imgPostTravel').addClass('shadow');
}, function() {
$('#imgPostTravel').removeClass('popout_image');
$('#imgPostTravel').removeClass('shadow');
});
$( "#imgPostTravel" ).hover(function() {
$(this).addClass('popout_image');
$(this).addClass('shadow');
}, function() {
$(this).removeClass('popout_image');
$(this).removeClass('shadow');
});
...whereas using .on( "hover", function() {...}
:
$( "#imgPostTravel" ).on( "hover", function() {
$('#imgPostTravel').addClass('popout_image');
$('#imgPostTravel').addClass('shadow');
}, function() {
$('#imgPostTravel').removeClass('popout_image');
$('#imgPostTravel').removeClass('shadow');
});
...does not.
Why not?
回答1:
That's because hover
is not an event name. Prior to jQuery 1.9 the library supported using this name, as is stated in the "Additional notes here:
Deprecated in jQuery 1.8, removed in 1.9: The name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.
Since it's not a standard event name, and the "special case support" that once existed is gone, it simply doesn't work...
回答2:
I guess you are using the on
method because you are adding the element dynamically.
Try with the following:
$(document).on( "mouseenter", "#imgPostTravel", function() {
$('#imgPostTravel').addClass('popout_image');
$('#imgPostTravel').addClass('shadow');
}, function() {
$('#imgPostTravel').removeClass('popout_image');
$('#imgPostTravel').removeClass('shadow');
});
Where document
should actually be the closest non-dynamically generated parent to the imgPostTravel
element.
UPDATE:
As it was pointed in another of the answers, hover
shouldn't be used and mouseover
or mouseenter
(depending on the desired functionality) should be used instead.
来源:https://stackoverflow.com/questions/32791289/why-does-the-onevent-function-style-of-jquery-event-handler-not-work-f