开发者

how to clone forms in javascript preserving event bindings

I am about to clone a part of form which has some actions bound to click events. 开发者_开发百科I want to change all occurences of word TEMPLATE in attributes to 'n_'+ID. I want to abstract from structure of cloned part - It would be one TEMPLATE or 10. I tried to something like this but the bindings are lost:

insert = function(){
    var old = $('#TEMPLATE');
    var copy = old.clone(true); 
    var html = old.html().replace(/TEMPLATE/g,'n'+next_ID);
    old.html(html);
    old.attr('id','n'+next_ID);
    old.show('fast');
    old.after(copy);
    next_ID++;
}

Is there any way to do it easily without knowing anything about the structure of the copied element.


No. You would have to re-add handlers each time.

If you really want to avoid this, use event delegation (delegate() or live()) to attach your event handlers. That way they are not associated with particular node objects, but only the placement of elements, whether they match a selector, at event firing time.

$(myform).delegate('.dosomething', 'click', function() {
    // handle clicks on any .dosomething in the form now or added later
});

(And try to avoid text processing over the html()/innerHTML. This is unreliable. It's better to iterate over objects whose names or classes you want to change doing it with attr.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜