2015-02-10 66 views
0

最后一个项目我做了以下内容:空()追加()附加在循环

$('.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

我该如何解决这个问题?

回答

2

您需要在循环之前将其清空,添加要删除以前的内容意味着以前所有的项目的任何项目因此被去除仅在循环中的最后一项兑现之前其他

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

您需要到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>"); 
    }); 
}); 

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

1

空,外循环,否则你将与去年追加元素只是作为一切它会被清空之前结束

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