代码之家  ›  专栏  ›  技术社区  ›  webwires

“移动”时丢失jquery项数据

  •  2
  • webwires  · 技术社区  · 17 年前

    本质上: 每次克隆项目时,都会丢失这些项目的data()值。

    长篇故事: 我有一个三列表,它存储从JSON对象动态输入的项目。每个项目都有一个我使用的数据值集。

    $.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);
           }
         });
       };
     });
    

    在这些项上有一个click事件,它使用存储为“l1”键的JSON数据,这些工作正常,但是……

    我允许使用文本框和“:not(:contains('text'))”选择器筛选这些项目。

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

    但是…因为我有三列,列可能是不均匀的,所以我试图通过克隆其余的列来将项目转换为三列。

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

    完成此操作后,click函数将不再查找任何data()值,即使它们以前已经工作过。

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

    如何保留与项一起存储的data()值?

    1 回复  |  直到 17 年前
        1
  •  4
  •   howardr    17 年前

    jquery的clone方法显式地从克隆的元素(jquery v1.3.1的第301行)中删除data()值:

            // 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;
            });
    

    您需要获取数据,然后将其重新添加到克隆的元素中。jquery的expando属性名不是公共变量。