jQuery:如何检查元素是否是动态添加的?

时间:2014-01-07 08:46:21

标签: jquery events

我有一个小工具提示。在某些地方,它会动态添加到页面上。在其他方面,它从一开始就存在。

因为像$("mytooltip").mouseover(...)这样的内容对于动态添加的元素不起作用,我必须使用类似$("body").on("mouseover, ".mytooltip", function(){...})

的内容

我很担心,对于第二个解决方案,每次我在body移动鼠标时都会尝试触发一个函数,效率非常低(对吧?)。

我想也许每当我动态添加工具提示时,我都可以触发某种自定义事件。这样,如果事件被触发,我们会切换到$("body").on("mouseover", .....);,否则,我们将使用普通的$(".mytooltip").mouseover

类似于:

    if(...){//Event was fired - i.e. we've added the tooltip dynamically
        $("body").on("mouseover", ".mytooltip", function(){
            mouseOverFunc();
        });
        $("body").on("mouseout", ".mytooltip", function(){
            mouseOutFunc();
        });
    }else{
       $(".mytooltip").mouseover(function(){
            mouseOverFunc();
        });
         $(".mytooltip").mouseout(function(){
            mouseOutFunc();
        });

    }

问题是,我不知道如何检测事件是否被触发......

PS - 奖金问题:我做的合理吗?或者我过度使用它,应该只为$("body").on("mouseover")做一切吗?

1 个答案:

答案 0 :(得分:0)

如果你动态添加html,你需要在ajax调用之后而不是在DOM中执行javascript

$.ajax{
    //do something
    $(div).html(code);
    if(...){//Event was fired - i.e. we've added the tooltip dynamically
        $("body").on("mouseover", ".mytooltip", function(){
            mouseOverFunc();
        });
        $("body").on("mouseout", ".mytooltip", function(){
            mouseOutFunc();
        });
    }else{
       $(".mytooltip").mouseover(function(){
            mouseOverFunc();
        });
         $(".mytooltip").mouseout(function(){
            mouseOutFunc();
        });
    }
}