我正在执行以下操作:
$('.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/