所以我试图将一个 div 插入另一个都是用 Javascript 创建的 我有以下代码,
// Assign tool attributes to Javascript Variables
var tool_name = String(tool['tool_name']);
tool_name = tool_name.replace(/'/g, '');
var tool_inventory_number = String(tool['tool_inventory_number']);
tool_inventory_number = tool_inventory_number.replace(/'/g, '');
var tool_recnum = String(tool['tool_recnum']);
tool_recnum = tool_recnum.replace(/'/g, '');
// Create the divs for the search results
var toolDiv = document.createElement("div");
var toolDivPicture = document.createElement("div");
//todo: Insert picture into this toolDivPicture div
var toolDivDescription = document.createElement("div");
toolDivDescription = toolDivDescription.innerHTML + "<h2>" + tool_name + "</h3>" + " <br>" + "Inventory Number: " + tool_inventory_number;
// Assign class to search result toolDiv and add content to it.
toolDiv.className = "toolDiv";
toolDiv.appendChild(toolDivDescription);
我不断收到以下错误,
未捕获的 NotFoundError:无法在“节点”上执行“appendChild”:新的子元素为空。
这可能是因为我必须通过 id 引用子 div 吗?我真的只想让 javascript 创建一个包含另外两个 div 的 div,然后将其插入到页面中。感谢任何帮助/建议!
最佳答案
由于您用 jQuery 标记标记了问题,我假设您已经加载了 jQuery 库:
// Create the divs for the search results
var toolDiv = $("<div/>");
var toolDivPicture = $("<div/>");
var toolDivDescription = $("<div/>");
toolDivDescription.html("<h2>" + tool_name + "</h3>" + " <br>" + "Inventory Number: " + tool_inventory_number);
// Assign class to search result toolDiv and add content to it.
toolDiv.addClass("toolDiv");
toolDiv.append(toolDivDescription);
请注意,您开始一个 h2 但结束一个 h3。
关于javascript - 如何将一个 div 插入另一个用 javascript 创建的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22842519/