简体   繁体   中英

how can I clone the current object in a click handler in javascript

I want to dynamically add textfield to the webform. There is 'add' icon beside the existing textfield. when clicking the icon, a new combination of 'add' icon and textfield are added. Then, it is the same situation with the new 'add' icon. How can do that in javascript or jquery framework?

Use the clone() method to clone an element.

$("#add").live("click", function(ev){
    var clone = $(ev.target).clone();
    //Add the clone to the document, eg: clone.appendTo("body");
})

See also: JQuery Docs - Clone .

Assuming something like:

<div><input><button>add</button></div>

Then try:

var elm;
$('button').click(function() {
    elm = $(this).parent();
    elm.after( elm.clone(true) );
});

Demo: http://jsfiddle.net/KL7QZ/2/

Passing true in the .clone method also clones events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM