将事件与对象一起克隆?

时间:2013-03-06 18:22:04

标签: javascript jquery dom

我的问题涉及克隆和克隆事件。

我有这个按钮:

<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 个答案:

答案 0 :(得分:4)

那是因为你在添加监听器之前克隆元素。

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

http://jsfiddle.net/j7XR9/