如何在.clone元素上添加事件处理程序

时间:2014-01-07 08:32:17

标签: jquery clone

我有一个表行,它是从父...

克隆的

以下是代码:

$(this).closest("tr").clone(true).off().attr("class", "newclass").appendTo("#comparelist");

我也添加了这段代码:

  $(".newclass").hover(function () {
        alert("hello");
    });

表行已成功克隆,但无法触发悬停功能..

有谁知道为什么会这样?

谢谢..

3 个答案:

答案 0 :(得分:4)

使用委派的事件处理程序

$("#comparelist").on({
   mouseenter : function () {
       alert("mouse entered");
   },
   mouseleave : function () {
       alert("mouse left");
   }
}, ".newclass");

并删除off()

var clone = $(this).closest("tr").clone(true);

clone.attr("class", "newclass");
clone.appendTo("#comparelist");

答案 1 :(得分:1)

试试这个:

    $(document).on('hover', '.newclass', function () {
        alert("hello");
    });

答案 2 :(得分:1)

您需要委托该元素上的事件,因为它是动态创建的。 因此,您可以使用livedeligateon事件绑定方法。我建议使用on方法。

以下是示例。

$(document).on("mouseenter", ".newclass", function () {
    alert("hello");
});

祝你好运!