2015-02-10 45 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>"); 
    }); 
});