我看到了this answer关于样式内部 li
元素,但我关心的是类似的东西:
<ul>
<li>
content
<ul>
<li> more content <li>
</ul>
</li>
</ul>
当设置样式时,如果我尝试将最外层的 li
设置为类似 border: 1px, solid, #333;
该框将包围嵌套在该 li 中的所有内容,而不仅仅是“内容”。
现在您可能会想“添加一个内部 div 来包裹您的内容,我不确定如何使用类似这样的东西来做到这一点:
renderComments: function(comments) {
// Return undefined if there are no comments to process;
// alternatively, it /may/ be appropriate to return an empty UL.
if (!comments || !comments.length) {
return;
}
// Create the container UL for the comments in this level.
var list = $('<ul>');
for (var i = 0; i < comments.length; i++) { // Don't use for..in for arrays
var comment = comments[i];
// Create an LI for each comment and add it to the container
var item = $('<li>')
.attr('id', "comment-" + comment.id);
// Add the LI to the UL parent
list.append(item);
// Add appropriate items to LI for comment
item.append($('<div>'));
item.append($('<h1>').text(comment.author));
item.append($('<p>').text(comment.comment));
// And then do the same for each child level of comments..
var childrenList = this.renderComments(comment.children);
if (childrenList) {
// ..adding children (UL) container to the current item (LI)
item.append(childrenList);
}
}
// Return container to be used by caller
return list;
},
这实际上为我创建了可以永远存在的嵌套列表(理论上)
最佳答案
问题是您要按顺序append
到li
元素,而不是将您的注释构造为树,然后将该结构附加到李
。尝试这样的事情:
var item = $('<li>').attr('id', "comment-" + comment.id);
var comment = $('<div>');
var author = $('<h1>').text(comment.author);
var commentText = $('<p>').text(comment.comment);
comment.append(author);
comment.append(commentText);
item.append(comment);
list.append(item);
这有一个额外的好处,即通过命名您正在创建的每个 DOM 节点,使您的代码更具可读性。
关于javascript - 样式化嵌套的 li 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24288599/