可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a <ul>
that is populated with javascript after the initial page load. I\'m currently using .bind
with mouseover
and mouseout
.
The project just updated to jQuery 1.7 so I have the option to use .on
, but I can\'t seem to get it to work with hover
. Is it possible to use .on
with hover
?
EDIT: The elements I\'m binding to are loaded with javascript after the document loads. That\'s why I\'m using on
and not just hover
.
回答1:
(Look at the last edit in this answer if you need to use .on()
with elements populated with JavaScript)
Use this for elements that are not populated using JavaScript:
$(\".selector\").on(\"mouseover\", function () {
//stuff to do on mouseover
});
.hover()
has it\'s own handler: http://api.jquery.com/hover/
If you want to do multiple things, chain them in the .on()
handler like so:
$(\".selector\").on({
mouseenter: function () {
//stuff to do on mouse enter
},
mouseleave: function () {
//stuff to do on mouse leave
}
});
According to the answers provided below you can use hover
with .on()
, but:
Although strongly discouraged for new code, you may see the
pseudo-event-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.
Also, there are no performance advantages to using it and it\'s more bulky than just using mouseenter
or mouseleave
. The answer I provided requires less code and is the proper way to achieve something like this.
EDIT
It\'s been a while since this question was answered and it seems to have gained some traction. The above code still stands, but I did want to add something to my original answer.
While I prefer using mouseenter
and mouseleave
(helps me understand whats going on in the code) with .on()
it is just the same as writing the following with hover()
$(\".selector\").hover(function () {
//stuff to do on mouse enter
},
function () {
//stuff to do on mouse leave
});
Since the original question did ask how they could properly use on()
with hover()
, I thought I would correct the usage of on()
and didn\'t find it necessary to add the hover()
code at the time.
EDIT DECEMBER 11, 2012
Some new answers provided below detail how .on()
should work if the div
in question is populated using JavaScript. For example, let\'s say you populate a div
using jQuery\'s .load()
event, like so:
(function ($) {
//append div to document body
$(\'<div class=\"selector\">Test</div>\').appendTo(document.body);
}(jQuery));
The above code for .on()
would not stand. Instead, you should modify your code slightly, like this:
$(document).on({
mouseenter: function () {
//stuff to do on mouse enter
},
mouseleave: function () {
//stuff to do on mouse leave
}
}, \".selector\"); //pass the element as an argument to .on
This code will work for an element populated with JavaScript after a .load()
event has happened. Just change your argument to the appropriate selector.
回答2:
None of these solutions worked for me when mousing over/out of objects created after the document has loaded as the question requests. I know this question is old but I have a solution for those still looking:
$(\"#container\").on(\'mouseenter\', \'.selector\', function() {
//do something
});
$(\"#container\").on(\'mouseleave\', \'.selector\', function() {
//do something
});
This will bind the functions to the selector so that objects with this selector made after the document is ready will still be able to call it.
回答3:
I\'m not sure what the rest of your Javascript looks like, so I won\'t be able to tell if there is any interference. But .hover()
works just fine as an event with .on()
.
$(\"#foo\").on(\"hover\", function() {
// disco
});
If you want to be able to utilize its events, use the returned object from the event:
$(\"#foo\").on(\"hover\", function(e) {
if(e.type == \"mouseenter\") {
console.log(\"over\");
}
else if (e.type == \"mouseleave\") {
console.log(\"out\");
}
});
http://jsfiddle.net/hmUPP/2/
回答4:
You can you use .on()
with hover
by doing what the Additional Notes section says:
Although strongly discouraged for new code, you may see the
pseudo-event-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.
That would be to do the following:
$(\"#foo\").on(\"hover\", function(e) {
if (e.type === \"mouseenter\") { console.log(\"enter\"); }
else if (e.type === \"mouseleave\") { console.log(\"leave\"); }
});
EDIT (note for jQuery 1.8+ users):
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.
回答5:
$(\"#MyTableData\").on({
mouseenter: function(){
//stuff to do on mouse enter
$(this).css({\'color\':\'red\'});
},
mouseleave: function () {
//stuff to do on mouse leave
$(this).css({\'color\':\'blue\'});
}},\'tr\');
回答6:
jQuery hover function gives mouseover and mouseout functionality.
$(selector).hover(inFunction,outFunction);
$(\".item-image\").hover(function () {
// mouseover event codes...
}, function () {
// mouseout event codes...
});
Source: http://www.w3schools.com/jquery/event_hover.asp
回答7:
Just surfed in from the web and felt I could contribute. I noticed that with the above code posted by @calethebrewer can result in multiple calls over the selector and unexpected behaviour for example: -
$(document).on(\'mouseover\', \'.selector\', function() {
//do something
});
$(document).on(\'mouseout\', \'.selector\', function() {
//do something
});
This fiddle http://jsfiddle.net/TWskH/12/ illustraits my point. When animating elements such as in plugins I have found that these multiple triggers result in unintended behavior which may result in the animation or code being called more than is necessary.
My suggestion is to simply replace with mouseenter/mouseleave: -
$(document).on(\'mouseenter\', \'.selector\', function() {
//do something
});
$(document).on(\'mouseleave\', \'.selector\', function() {
//do something
});
Although this prevented multiple instances of my animation from being called, I eventually went with mouseover/mouseleave as I needed to determine when children of the parent were being hovered over.
回答8:
You can provide one or multiple event types separated by a space.
So hover
equals mouseenter mouseleave
.
This is my sugession:
$(\"#foo\").on(\"mouseenter mouseleave\", function() {
// do some stuff
});
回答9:
For elements that are added dinamically, see http://api.jquery.com/on/. I am quoting main parts:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). If new HTML is being injected into the page, it is prefferable to use delegated events to attach an event handler, as described next.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, this example attaches a handler to 1,000 elements:
$(\"#dataTable tbody tr\").on(\"mouseenter\", function(event){
alert($(this).text());
});
A delegated-events approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the tr to tbody):
$(\"#dataTable tbody\").on(\"mouseenter\", \"tr\", function(event){
alert($(this).text());
});
Note: Delegated events do not work for SVG.
回答10:
If you need it to have as a condition in an other event, I solved it this way:
$(\'.classname\').hover(
function(){$(this).data(\'hover\',true);},
function(){$(this).data(\'hover\',false);}
);
Then in another event, you can easily use it:
if ($(this).data(\'hover\')){
//...
}
(I see some using is(\':hover\')
to solve this. But this is not (yet) a valid jQuery selector and does not work in all compatible browsers)
回答11:
The jQuery plugin hoverIntent http://cherne.net/brian/resources/jquery.hoverIntent.html goes much further than the naive approaches listed here. While they certainly work, they might not necessarily behave how users expect.
The strongest reason to use hoverIntent is the timeout feature. It allows you to do things like prevent a menu from closing because a user drags their mouse slightly too far to the right or left before they click the item they want. It also provides capabilities for not activating hover events in a barrage and waits for focused hovering.
Usage example:
var config = {
sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
interval: 200, // number = milliseconds for onMouseOver polling interval
over: makeTall, // function = onMouseOver callback (REQUIRED)
timeout: 500, // number = milliseconds delay before onMouseOut
out: makeShort // function = onMouseOut callback (REQUIRED)
};
$(\"#demo3 li\").hoverIntent( config )
Further explaination of this can be found on https://stackoverflow.com/a/1089381/37055