empty().append()追加循环中的最后一项
empty().append() appending last item in loop
我正在执行以下操作:
$('.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>");
});
});
相关文章:
- 如何从对象数组中获取最后一项
- 为什么只有最后一项显示,而不是全部显示
- 删除最后一项jquery
- 为什么我的“for”循环只获取 html 中的最后一项
- 我无法将下拉列表的默认值设置为最后一项
- 流星批量插入仅插入最后一项
- 我怎么能知道元素是最后一项
- 如何删除WinJS组绑定列表的最后一项
- 使用handlers.js模板以数组中的最后一项为条件
- empty().append()追加循环中的最后一项
- jQuery只附加最后一项
- 将属性添加到 for 循环中的最后一项
- 如何按排序键顺序获取对象中的最后一项
- for 循环中的 addEventListener 始终添加到最后一项
- 从数组中删除最后一项
- CasperJS只从我的for循环中多次发布最后一项
- 在 JavaScript 中处理数组中的最后一项
- 胡子.js带有数组,最后一项除外
- 通过jQuery在最后一项之后插入
- JavaScript for 循环只返回数组中的最后一项