javascript - 样式化嵌套的 li 元素

标签 javascript jquery html css

我看到了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;
  },

这实际上为我创建了可以永远存在的嵌套列表(理论上)

最佳答案

问题是您要按顺序appendli 元素,而不是将您的注释构造为树,然后将该结构附加到。尝试这样的事情:

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 节点,使您的代码更具可读性。

并确保查看 append 的 jQuery 文档和 appendTo看看另一个是否更适合您的用例。

关于javascript - 样式化嵌套的 li 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24288599/

相关文章:

jquery - 用于视差滚动的 Stellar.js 已删除

javascript - 将 JQuery 脚本与外部文件中的选择器分开不起作用?

html - div.fixed 100% 宽度只用 css

javascript - 追加不受 javascript 影响的 jQuery 值

javascript - 迭代对象和数组 javascript/Angular

php - 在数据库中逐一获取值之间等待

javascript - 通过弹窗搜索MySQL数据

html - 在哪里可以找到支持多种分辨率/浏览器的免费 html 模板?

javascript - 使用短路评估来定义变量

javascript - iframe 链接在 iframe 内重定向