Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

jquery - Using delegate() with hover()?

I have a ul element with many li items:

<ul>
    <li></li>
    ...
</ul>

when the user hovers their mouse over an li element, I'd like show some hidden buttons on the li, when they stop hovering, hide the buttons again. Trying to use delegate:

$("#myList").delegate("li", "hover", function () {
    if (iAmHovered()) {
        showButtons();
    } else {
        hideButtons();
    }
});

the above gets called for both hover and 'un-hover'. How can I distinguish if it's a leave or enter though?

Also, I got this sample from this question: .delegate equivalent of an existing .hover method in jQuery 1.4.2

in which Nick says:

This depends on [#myList] not getting replaced via AJAX or otherwise though, since that's where the event handler lives.

I do replace the contents of #myList though, using:

$("#myList").empty();

will that cause a problem?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to test for the type of event, like this:

$("#myList").delegate("li", "hover", function ( event ) {
    if (event.type == 'mouseover') {
        showButtons();
    } else {
        hideButtons();
    }
});

Since there's only one handler to run for both events, we are checking to see which one fired, and running the appropriate code.

As opposed to binding hover directly to the element where it is able to accept two handlers for the two event types.


EDIT: Note that as of jQuery 1.4.3, the type of event that is reported when using 'hover' with .delegate() or .live() is no longer mouseover/mouseout (as it ought to be). Now it will be mouseenter/mouseleave, which just seems silly since they're non-bubbling events.

So the if() statement would look like:

if (event.type == 'mouseenter') {
    //...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...