2013-03-06 139 views
0

我的问题涉及克隆和克隆事件。将事件与对象一起克隆?

我有这个按钮:

<button type="button" class="btn btn-inverse test">test</button> 

在我的JS:

//create a clone of my button at the start so any later changes to the btn do not effect future clones 
var test = $(".test").clone(true); 

$(".test").click(function() { 
    alert('a'); 
}); 

test.clone(true).insertBefore('#addQuestion'); 

以上克隆的按钮,但该事件不再工作,我要去哪里错了?

+1

哪个事件不再起作用? – SLaks 2013-03-06 18:23:54

+0

那么,至少在你的代码示例中,你是在克隆'$(“。test”)'(在第2行)后分配处理程序。 – kay 2013-03-06 18:25:32

+0

请参阅 http://api.jquery.com/clone/ – 2013-03-06 18:30:32

回答

4

这是因为您在添加侦听器之前克隆了元素。

var test = $(".test").click(function() { 
       alert('a'); 
      }).clone(true); // .insertBefore('#addQuestion') 

http://jsfiddle.net/j7XR9/