jQuery实时悬停 [英] jQuery live hover

查看:72
本文介绍了jQuery实时悬停的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法将以下内容转换为实时悬停

I can't seem to convert the following into a live hover

$("li.favorite_item").hover(
    function () {
        $(this).append($(" <a href='#' class='button'>x</a>"));
    }, 
    function () {
        $(this).find("a:last").remove();
    }
);

我尝试过:

$("li.favorite_item"").live('hover', function() { 
    function () {
        $(this).append($(" <a href='#' class='button'>x</a>"));
    }, 
    function () {
        $(this).find("a:last").remove();
    }
});

但是它不起作用.

推荐答案

从jQuery 1.7+开始,.live()已 已弃用 ,而.delegate()已被.on 取代 ()方法.

From jQuery 1.7+ .live() is deprecated, and .delegate() has been superseded by the .on() method.

使用 .on() .off()代替.live()和.die().使用.on()代替.delegate().

Use .on() and .off() in place of .live(), and .die(). Use .on() in place of .delegate().

转换旧代码很简单如此处所述.

您需要分别调用 .hover() 映射到的事件,像这样:

You need to call the events that .hover() maps to separately, like this:

$("li.favorite_item").live('mouseenter', function() { 
  $(this).append($(" <a href='#' class='button'>x</a>"));
}).live('mouseleave', function () {
  $(this).find("a:last").remove();
});

.hover() 不是类似只是.mouseenter(handler1).mouseleave(handler2) 的特殊快捷方式...因此您需要在 .live() 致电.

.hover() isn't an event function like .click() is for example, it's just a special shortcut for .mouseenter(handler1).mouseleave(handler2)...so you need to do the same in your .live() call.

如果您使用的是jQuery 1.4.3+,则可以使用地图来简化操作,例如:

If you're on jQuery 1.4.3+, you can use a map to simplify things, like this:

$("li.favorite_item").live({
  mouseenter: function() { 
    $(this).append($(" <a href='#' class='button'>x</a>"));
  },
  mouseleave: function () {
    $(this).find("a:last").remove();
  }
});

此外,如果这是在特定的<ul>上,则 .delegate() 是更好的选择,例如:

Also, if this is on a specific <ul>, .delegate() is a better option, like this:

$("#myUL").delegate("li.favorite_item", {
  mouseenter: function() { 
    $(this).append($(" <a href='#' class='button'>x</a>"));
  },
  mouseleave: function () {
    $(this).find("a:last").remove();
  }
});

这篇关于jQuery实时悬停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆