Jquery .html没有删除元素内容

时间:2015-10-15 04:13:04

标签: javascript jquery html

美好的一天。

我的场景是我想在某个标签上添加一个新元素ul li,该元素对应于他们自己的id。代码工作正常..但我发现.append比.html慢得多...你在我的代码中看到如果我将.append更改为.html它只会显示最后一个循环。 ..从.html删除里面的现有元素并替换一个新元素......

我想要的是通过.html显示它们的ID。

物件

groups = [{
    GroupID: 1,
    tabPaneID: "home"
  },

  {
    GroupID: 2,
    tabPaneID: "edit"
  },

  {
    GroupID: 3,
    tabPaneID: "view"
  },

  {
    GroupID: 4,
    tabPaneID: "home"
  },

  {
    GroupID: 5,
    tabPaneID: "home"
  }
];

items = [{
  GroupID: 1,
  Item: "SampleItem1",
  Qty: 21
}, {
  GroupID: 1,
  Item: "SampleItem2",
  Qty: 21
}, {
  GroupID: 2,
  Item: "SampleItem3",
  Qty: 22
}, {
  GroupID: 3,
  Item: "SampleItem4",
  Qty: 23
}, {
  GroupID: 4,
  Item: "SampleItem5",
  Qty: 24
}, {
  GroupID: 4,
  Item: "SampleItem6",
  Qty: 25
}, {
  GroupID: 5,
  Item: "SampleItem7",
  Qty: 25
}];

JQUERY

$.each(settings.tabs, function (i, t) {
  $.each(settings.group, function (ObjID, groupObj) {
    if (t.tabPaneID == groupObj.tabPaneID) {
      $tabPane.find("#" + t.tabPaneID).append("<ul class='delta-ui-common-ul' id=group-" + groupObj.GroupID + "></ul>");

      $.each(settings.item, function (itemID, itemObj) {
        if (groupObj.GroupID == itemObj.GroupID) {
          var list = $tabPane.find("#" + t.tabPaneID);
          list.find("#group-" + groupObj.GroupID).append("<li>" + itemObj.Item + "</li>");

        }
      });
    }
  });
});

2 个答案:

答案 0 :(得分:1)

因为替换了html(),你必须自己进行追加,例如:

var current_html = list.find("#group-"+groupObj.GroupID).html();
list.find("#group-"+groupObj.GroupID).html(current_html+"<li>"+itemObj.Item+"</li>");

jQuery.append()不只是向元素添加文本,因此jQuery.html()的速度要快得多。

答案 1 :(得分:0)

使用innerHTML。它比appendhtml快。
如下所示

<span id='foo'>I am </span>
<script>
  document.getElementById('foo').innerHTML += '<b>HTML</b>'
</script>

  

.append VS .html VS .innerHTML performance