我有一个for
循环,该循环使用一个函数创建了一些DOM元素。 for循环成功执行了几次,但突然出现错误,我不明白为什么。
我在代码中添加了一些console.log
以帮助您理解,我将在问题末尾添加控制台的屏幕截图。
这是代码的第一部分:
if(comments.length > 0) {
for(let k = 0; k < comments.length; k++) {
console.log('in the for 1')
createComment(commentContainer,comments[k])
console.log('in the for 2')
}
console.log('after the for') // We never reach this console.log
}
然后是createComments()
函数:
let createComment = (container, data, answer = true) => {
console.log('Start createComment')
let newCommentPart = container.getElementsByTagName('textarea')[0]
let singleCommentContainer = createNodeBefore(container, newCommentPart, 'div', '')
if(answer === true){
let answeringContainer = createNode(singleCommentContainer, 'span', '')
let answeringButton = createNode(singleCommentContainer, 'span', `text random`)
if(data.answers && data.answers.length > 0) {
for(let i = 0; i < data.answers.length; i++) {
createComment(answeringContainer, data.answers[i], false)
}
}
let answerPostCommentInput = createNode(answeringContainer, 'textarea', '')
let answerPostCommentButton = createNode(answeringContainer, 'span', 'Some text')
}
console.log('End createComment')
}
最后,这是我用来创建元素的createNode()
和createNodeBefore()
函数:
let createNode = (parent, type, text, id = false, className = false, style = false) => {
console.log('createNode :' + type)
let textNode = document.createTextNode(text)
let element = document.createElement(type)
element.className = className ? className : "";
element.id = id ? id : "";
element.style = style ? style : "";
element.appendChild(textNode)
parent.appendChild(element)
console.log('Element :' + element)
return element
}
let createNodeBefore = (parent, node, type, text, id = false, className = false, style = false) => {
let textNode = document.createTextNode(text)
let element = document.createElement(type)
element.className = className ? className : ""
element.id = id ? id : ""
element.style = style ? style : ""
element.appendChild(textNode)
parent.insertBefore(element, node)
return element
}
因此该函数可以多次正确执行,但是由于某种原因它会停止工作。通过仔细观察,我可以确定不起作用的代码部分是createComment()
函数的这一部分:
let createComment = (container, data, answer = true) => {
console.log('Start createComment')
let newCommentPart = container.getElementsByTagName('textarea')[0]
console.log(newCommentPart)
console.log(container)
let singleCommentContainer = createNodeBefore(container, newCommentPart, 'div', '')
console.log('We never reach this part')
另一个很奇怪的事情是,在createComment()
函数中,如果我替换
let answerPostCommentInput = createNode(answeringContainer, 'textarea', '')
通过
let answerPostCommentInput = createNode(answeringContainer, 'span', '')
一切正常,我没有任何错误。
请随时问我是否需要更多详细信息或不清楚的地方。
编辑