gpt4 book ai didi

javascript - 构建一个 JS 函数来动态创建 HTML 元素并将它们相互嵌套

转载 作者:可可西里 更新时间:2023-11-01 13:51:09 32 4
gpt4 key购买 nike

我创建了下面的函数来动态创建 HTML 元素并将它们附加到我想要的任何位置。控制台在运行时不会记录任何错误,但第二个元素( <p> )不写入文档。

我认为错误与“createdDiv”变量有关,但我无法找出问题所在。

如有任何帮助,我们将不胜感激!

//Array of elements to be created

var createdElements = [
[ 'div', 'Class0', 'ID0'],
['p', 'Class1', 'ID1']
];


//function to create and append elements to document

function createHTML( typeOfCreatedElement ,createdElementClass, createdElementId, locationForCreatedElement ){
var createdElement = document.createElement( typeOfCreatedElement );
createdElement.className = createdElementClass;
createdElement.id = createdElementId;

locationForCreatedElement['appendChild']( createdElement );

return createdElement;
}


//run function 2x;
//createdDiv successfully writes to the document, but createdParagraph disappears into a black hole...

var createdDiv = createHTML( createdElements[0][0], createdElements[0][1], createdElements[0][2], document.body );
var createdParagraph = createHTML( createdElements[1][0], createdElements[1][1], createdElements[1][2], createdDiv );

最佳答案

你能试试这个更新的createHTML method()吗

function createHTML( typeOfCreatedElement ,createdElementClass, createdElementId, locationForCreatedElement ){
var createdElement = document.createElement( typeOfCreatedElement );
createdElement.className = createdElementClass;
createdElement.id = createdElementId;
createdElement.innerHTML = "this is a sample text for element type " + typeOfCreatedElement;

locationForCreatedElement.appendChild( createdElement ); //line that I have changed.

return createdElement;
}

appendChild是方法,不是属性。

关于javascript - 构建一个 JS 函数来动态创建 HTML 元素并将它们相互嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34243095/

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