简体   繁体   中英

Issue with event delegation

I am trying to clone a table once the table has been populated. Inside the td I placed some input and textarea tags. The problem that I have is that the contents inside the table are not cloned. I have tried to use event delegation, but it seems that I am doing something wrong. Here is the JSfiddle, write something inside the table and then press clone.`` http://jsfiddle.net/no84bror/2/

  $("#clonetable").on('click','textarea',function(){
    var tempTable = $('#masterTable');
    var temClone = $("<div/>").append(tempTable.clone()).html(); 
   // alert(temClone);
    var rep = temClone.replace("textarea","p");
    $("#a").html(rep);
    });

This is a jquery bug - deep cloning does not work for textareas http://bugs.jquery.com/ticket/3016 It started as a problem in Firefox but is the same in Chrome, apparently.

"The current behavior is documented at api.jquery.com and of course here. A plugin is available to provide the requested behavior. The ticket is marked patchwelcome, with the caveat that fixing this edge case inside jQuery causes a performance hit for the 90% of the time when it isn't needed."

The following code works and copies the contents of the input field, but due to the above bug you will have to copy the contents of textareas yourself or use the plugin.

$("#clonetable").on('click', function(){
     $("#a").html($('#masterTable').clone());
});

you can try using .clone( [withDataAndEvents][, deepWithDataAndEvents] ) , in other words using .clone(true, true) , but it makes no difference.


Here's the code, including the hack to copy textarea content:

 $("#clonetable").on('click',function(){
    $("#a").html($('#masterTable').clone());
    var my_textareas     = $('#masterTable textarea').slice(2,4);
    var result_textareas = $("#a textarea");

    for (var i = 0, l = my_textareas.length; i < l; ++i){
        $(result_textareas[i]).val($(my_textareas[i]).val());
    }
 });

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