empty().append()追加循环中的最后一项

empty().append() appending last item in loop

本文关键字:最后 一项 循环 append 追加 empty      更新时间:2023-09-26

我正在执行以下操作:

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

您需要empty()循环外的包含元素,否则在每次迭代时都会清除它。

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

请注意,我通过在声明变量时设置值来稍微缩短逻辑。

在循环外清空它,否则您将以只将最后一个元素作为清空之前的所有元素来结束

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