javascript - 将 HTML 元素存储在变量中
问题描述
<!DOCTYPE html>
<html>
<body>
<ul id="myList">
<li>Coffee</li>
<li>Tea</li>
</ul>
<p>Click the button to append</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
let newLi = document.createElement("LI");
let textNode = document.createTextNode("Water");
let water = newLi.appendChild(textNode);
console.log(water); // water variable doesn't store the node object that represents the appended node
document.getElementById("myList").appendChild(water);
}
</script>
</body>
</html>
我对 appendChild() 方法的返回值有疑问。定义说 appendChild() 的返回值是“表示附加节点的节点对象”。它不是字符串数据类型。所以,我只是试图将返回值存储在一个变量中(上面代码中的水变量)。但是,该变量只存储一个字符串数据类型。那是因为变量不能将 HTML 元素存储为它的值吗?
解决方案
appendChild 确实返回附加的节点。当您使用 createTextNode('water') 时,您会注意到它也只返回文本。那是因为 textNode 只是文本。
如果您将 appendChild 与 html 元素一起使用,而不仅仅是 textNode,那么它将返回完整的元素。
在你的情况newLi
下
<li>Water</li>
如果你有
let newLi = document.createElement("LI");
let newSpan = document.createElement("SPAN");
let textNode = document.createTextNode("Water");
let water = newSpan.appendChild(textNode);
let waterItem = newLi.appendChild(newSpan);
这里waterItem
是<span>Water</span>
。
推荐阅读
- c - PIC 18F45K42:如何将 4 个字节组合成 Int?
- javascript - 在单击事件上获取正确的 jquery 数据表对象
- c++ - noPoll Websocket 非阻塞处理程序
- openapi - 如何使用略有不同的 $ref 使用相同的组件模式?
- gitlab-ci - 使用 Gitlab CI 为 Hugo 站点创建 (HTML/PDF) 资产
- php - 未获取所有属性 PHP XPATH 的值
- sql-server - 使用 SSIS :使用 REST API 或直接查询数据库之间有什么更好的选择?
- scala - Scala lift 的 CssBind.calculate 不适用于 Seq
- python - 如何从多个列表的每个唯一组合创建熊猫数据框?
- android - 如何将图像转换为 base64 并在 androidX 中使用 kotlin 对其进行压缩?