将 .append() 与列表一起使用会将文本放在换行符上

Using .append() with lists places text on a newline

本文关键字:文本 换行符 append 列表 一起      更新时间:2023-09-26

>我正在尝试在javascript中创建一个无序列表。 我的代码如下:

$(div).append("<ul>")
for (i in usersLst){
    $(div).append("<li>")
    $(div).append(usersLst[i][1])
    $(div).append("</li>")
}
$(div).append("</ul>")

那么结果是:

•
bob
•
alice
•
fred

但是,如果代码显示:

$(div).append("<ul>")
for (i in usersLst){
    $(div).append("<li>"+usersLst[i][1]+"</li>")
}
$(div).append("</ul>")

那么结果是:

 - bob
 - alice
 - fred

因此,通过三个单独的附加,似乎正在神秘地插入换行符。 这是怎么回事?

假设以下代码:

$('div')
    .append("<ul>")
    .append("<li>");
    .append('foo');
    .append("</li>")
    .append("</ul>")​​​

让我们看一下结果结构(Chrome 21):

<div>
    <ul></ul>
    <li></li>
    foo
</div>

发生了什么事? .append 接受每个参数并将字符串转换为正确的 DOM 元素。因此,代码与执行相同:

$('div')
   .append(document.createElement('ul'))
   .append(document.createElement('li'));
   .append(document.createTextNode('foo'));

包含结束标记的两个调用将被忽略,因为它们无法转换为有效的HTML/DOM元素。

.append(以及所有其他 DOM 操作方法)正在处理 DOM 元素。这只是jQuery调用.appendChild[MDN]的方式。

HTML 只是表示结构的一种特定格式。其中,每个元素都由一个开始标签和一个(可选)结束标签表示。浏览器正在解析 HTML 并在内存中创建 DOM。DOM(文档对象模型)是一个定义良好的接口,用于与分层结构化数据进行交互。一旦你使用 DOM,开始和结束标签就不再存在(即 HTML),只有节点。我建议在 MDN 上阅读有关 DOM 的信息。

jQuery允许你将HTML字符串传递给.append因为它很方便,但每个字符串都会立即转换为相应的DOM节点并附加到其他节点。不能生成具有多次调用的 HTML 字符串 .append

这是代码的更正版本:

// jQuery parses the HTML string and creates a UL element
var $ul = $('<ul />');
// equivalent to
// var $ul = document.createElement('ul'); <- NOTE: not HTML, it's a node name
for (var i in usersLst) {
    // jQuery parses the HTML, creates a LI element and appends it to the list
    $ul.append('<li>' + usersLst[i][1] + '</li>');
    // equivalent to
    // var li = document.createElement('li');
    // li.appendChild(document.createTextNode(usersLst[i][1]));
    // $ul.appendChild(li);
}
// append the populated UL element to an existing node:
$(div).append($ul);
// equivalent to
// existingElement.appendChild($ul);

它们都是不正确的。您应该首先创建整个字符串,然后将其附加到 DIV:

var ul = '<ul>';
for (i in usersLst){
    ul+='<li>' + usersLst[i][1] + '</li>';
}
ul+='</ul>';
$(div).append(ul)