gpt4 book ai didi

javascript - 为什么 JavaScript 函数不创建 HTML 元素?

转载 作者:行者123 更新时间:2023-11-28 17:10:15 25 4
gpt4 key购买 nike

我有一个方法,旨在在另一个 div 中创建 div...但是它不起作用...

方法如下:

populateSquares(){
let relatedTagToPopulation = document.getElementById("questionp");
let whatTextIs = relatedTagToPopulation.textContent;
for (let u=0;u<this.stemQuestions.length;u++){
if (this.stemQuestions[u]==whatTextIs){
var populateSquaresPertinentInt = u;
}
}
for (let i=0;i<this.stemAnswers.length;i++){
if (i==populateSquaresPertinentInt){
let numberOfSquaresToAdd = this.stemAnswers[i].length;
for (let j=0;j<numberOfSquaresToAdd;j++){
let elToAdd = document.createElement("<div id='ans"+j+"' class='lans'></div>");
let elToAddInto = document.getElementById("answeri");
elToAddInto.appendChild(elToAdd);
}
}
}
}

它给出了这个错误...

Uncaught DOMException: Failed to execute 'createElement' on 'Document': The tag name provided ('<div id='ans0' class='lans'></div>') is not a valid name.

最佳答案

如果您使用 JavaScript,则应遵循文档:https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement ,这里:CreateElement with id?

let elToAdd = document.createElement('div')
// then call `elToAdd.xxxx` to add attributes or do other operation on the element
elToAdd.setAttribute("id", "ans" + i);
// ... more

如果您使用 jQuery,则可以使用:

let elToAdd = jQuery("<div id='ans"+j+"' class='lans'></div>")

关于javascript - 为什么 JavaScript 函数不创建 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54613777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com