javascript - empty().append() 附加循环中的最后一项

标签 javascript jquery

我正在执行以下操作:

$('.document-content').on('input', function() {
  var headers;
  headers = $('.document-content > h2').each(function() {
    var headerId, headerText;
    headerId = $(this).attr('id');
    headerText = $(this).text();
    $('.document-outline').empty().append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
  });
});

为了避免重复,我添加了 empty() 但现在只有每个 loop 中的最后一项被附加到 .document-outline.

我该如何解决这个问题?

最佳答案

您需要在循环之前清空它,否则在添加任何项目之前,您将删除以前的内容,这意味着所有以前的项目都被删除,因此仅保留循环中的最后一个项目

$('.document-content').on('input', function () {
     var $ct = $('.document-outline').empty();
    var headers;
    headers = $('.document-content > h2').each(function () {
        var headerId, headerText;
        headerId = $(this).attr('id');
        headerText = $(this).text();
        $ct.append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
    });
});

关于javascript - empty().append() 附加循环中的最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28427605/

相关文章:

javascript - jQuery 脚本只有在函数之上时才有效

javascript - 如何使用 Raphael .animateWith()

javascript - 动态更改视频字幕语言

javascript - highstock 图中同系列线的颜色不同?

jquery - nodejs 或 envjs - 动态 jquery tmpl

javascript - jQuery 捕获 iPad 或 iPhone 上的滚动事件与网络浏览器不一致

javascript - 在 Javascript 中查找请求 URL

javascript - 对同位素中的动态元素进行排序

javascript - 如何让插件的默认设置访问最终设置?

javascript - 获取 ( ) 中的内容并稍后使用