【问题标题】:Jquery .html without deleting element contentJquery .html 不删除元素内容
【发布时间】:2015-10-15 04:13:04
【问题描述】:

大家好。

我的场景是我想在某个标签上添加一个新元素 ul li,它对应于他们自己的 id。代码运行良好.. 但是我发现 .append 比 .html 慢得多...您在我的代码中看到如果我将 .append 更改为 .html 它只会显示最后一个循环...因为@ 987654324@删除里面已有的元素,换一个新的...

我想要通过.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>");

        }
      });
    }
  });
});

【问题讨论】:

  • @Tushar 有什么区别?它比 append 或 .html 快吗?
  • 在循环中创建一串HTML标记,然后在循环后使用html更新
  • @Tushar 那么我怎么知道我将放置 htmlstring 的哪个元素?因为它与id有关?

标签: javascript jquery html


【解决方案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() 更快。

【讨论】:

    【解决方案2】:

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

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

    .append VS .html VS .innerHTML performance

    【讨论】:

    • 虽然不起作用..我不知道为什么..我也尝试过这种方法。
    • 你能不能提供一个小提琴,我试试玩。
    • 没有。您不能将它与 jquery 选择器一起使用
    • 这样做document.getElementById("#group-"+groupObj.GroupID).innerHTML+="&lt;li&gt;"+itemObj.Item+"&lt;/li&gt;"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 2013-07-18
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    相关资源
    最近更新 更多