tags:

views:

413

answers:

1

In essence: every time I clone items I lose the data() value for those items.

The long story: I have a three column table that is storing items dynamically entered from a JSON object. Each of these items has a data value set that I use.

$.getJSON(jsonUrl, null, function(data) {
   jsonData = data.items;
   for (var key in jsonData) {
     lZeroArray.each(function() {
       if ($.trim($(this).text()) == $.trim(jsonData[key].name)) {
         $(this).data("L1", jsonData[key].L1);
       }
     });
   };
 });

there is a click event on these items that uses the JSON data stored as the "L1" key and these work fine but ...

I allow these items to be filtered using a text box and the ":not(:contains('text'))" selector.

$(".subMenuItem:not(:contains('" + str + "'))").remove();

but ... because I have three columns the columns can be uneven so I attempt to resort the items into the three columns by cloning the remaining ones.

var items = $(".subMenuItem").clone(true);
$("#subMenuContent td").empty();
addItemsToColumn(items);

After I do this the click functions no longer find any of the data() values even though they workled before.

$(".subMenuItem").live("click", function() {
  if ($(this).data("L1")) {
    buildSubMenuItems($(this).data("L1"));
  }
});

How do I retain the data() values that I store with an item?

+2  A: 

jQuery's clone method explicitly removes the data() values from the cloned elements (line 301 of jQuery v1.3.1):

     // Need to set the expando to null on the cloned set if it exists
     // removeData doesn't work here, IE removes it from the original as well
     // this is primarily for IE but the data expando shouldn't be copied over in any browser
     var clone = ret.find("*").andSelf().each(function(){
      if ( this[ expando ] !== undefined )
       this[ expando ] = null;
     });

You'll need grab the data then re-add it to the cloned elements. jQuery's expando property name is not a public variable.

howardr
Here is an example of how you might copy over the data: var data = $.map( $(".subMenuItem"), function(elem) { return $(elem).data('L1') } ); var items = $(".subMenuItem").clone(true).each(function(i) { $(this).data('L1', data[i]) }); $("#subMenuContent td").empty(); addItemsToColumn(items);
howardr
according to those comments IE removes the data from the original as well. Am I reading that right?
webwires
thanks this worked very well.
webwires