使用.live()和item.length绑定事件失败

bind event with .live() and item.length fails

本文关键字:length 绑定 事件 失败 item live 使用      更新时间:2023-09-26

我正在为我的网站制作一个小的工具提示功能

我做得很好:(在项目悬停时检查是否存在气泡并显示它。如果不存在,则发出请求,附加气泡,然后显示它)

$('.profileIcon').hover(function(){
    var u = $(this);
    var url = $(this).find('a').attr('href')+' #intro_usuario';
    if($(this).find('.nube').length>0){
        $(this).find('.nube').show();
    } else {
        //$('<div>').load(url).addClass('nube').css({'left':$(this).offset().left+$(this).outerWidth(true)+15,'top':$(this).offset().top}).appendTo(this).show();
        $('<div>').addClass('nube').addClass('nubeU').load(url,function(){
            $(this).css({'left':-20,'top':-16}).appendTo(u).show();
        });
    }
});

它只会在用户第一次悬停时发出请求并附加toolip(.nube)div,下次只会显示它(没有请求)。

但在使用ajax加载更多元素时,我不得不回忆它,所以我很难使用实时

$('.profileIcon').live('hover',function(){
    var u = $(this);
    var url = $(this).find('a').attr('href')+' #intro_usuario';
    if($(this).find('.nube').length>0){
        $(this).find('.nube').show();
    } else {
       //$('<div>').load(url).addClass('nube').css({'left':$(this).offset().left+$(this).outerWidth(true)+15,'top':$(this).offset().top}).appendTo(this).show();
       $('<div>').addClass('nube').addClass('nubeU').appendTo(u).html($('#load').html()).load(url,function(){
           $(this) .css({'left':-20,'top':-16}).show();
       });
    }
});

请求每次都会完成,每次都会附加一个额外的气泡

问题是:

?为什么if($(this).find('.nube').length>0停止使用live工作?

我不会在.live()上浪费时间,转而使用新的替代品。on()

.on()的工作方式类似于直接绑定到事件,但也类似于live。有关如何直接绑定和"气泡绑定"的详细信息,请阅读文档。

尝试用.on()替换.live(),它们应该可以正常工作。

对于直接绑定(将处理程序附加到元素):

element.on('event',function(){});

对于"bubble-bind"(请注意,element现在是第二个参数,并且为父级提供了处理程序。子级将被触发,事件将冒泡到父级来处理事件)

someParentElement.on('event','element',function(){});

此外,当使用.on()时,您不必担心this是谁,它将始终是您触发的元素,无论是直接触发还是在气泡中触发。