2013-03-06 140 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/