我得到了一些带有属性“title”的对象。
当主体加载时,我想为现有的每个对象创建一个新的 div。
当我这样做时,div 容器不会被创建,并且现在控制台中列出了错误。
重要提示:显然,我的节点列表不为空。我有一个包含 10 个对象的测试例程。因此,当我在 createNodeContainer
函数中写入时
console.log(node.title);
它正确地写下了对象的标题。所以我有“内容”,但没有将 div 容器添加到 div“nodeList”
所以我当前的代码如下所示:
function loadNodes(){
var nodes = store.getNodes(); // get all the objects from a list
for (var i = 0; i < nodes.length; i++) {
createNodeContainer(nodes[i]); // pass in the current node of the nodeList
}
}
function createNodeContainer(node){ // create the new div
var newNodeContainer = document.createElement("div");
newNodeContainer.class = "nodeContainer"; // add some css
newNodeContainer.innerHTML = node.title; // write a text for testing it
$('nodeList').append(newNodeContainer); // add it to the parent div
}
我的 Html 是这样的:
<body onLoad ="loadNodes()">
<div id="nodeList">
</div>
</body>
有人可以帮我吗?
最佳答案
我正在使用 jQuery,
var createNodeContainer = function(node){
var newContainer = '<div class="nodeContainer">'; //Create a div with nodeContainer class
newContainer += node.title; //Add title within div
newContainer += '</div>'; //Close your div
console.log(newContainer); //Check the created div container
$('#nodeList').append(newContainer); //Append created containerto the parent div
}
这段代码肯定会有帮助。
关于javascript - 动态创建 div 容器并将它们添加到现有的 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44613138/