我目前正在尝试创建一个函数,该函数创建一个具有提交按钮的表单,并且默认情况下处于隐藏状态,直到从另一个按钮触发为止。我的按钮当前会按照我的意愿弹出表单,但在表单中我的添加按钮不存在,而且我也无法实际添加到表单,因为它说appendChild为空。但检查服务器和查询都表明找到了该值。下面是我的错误的具体代码片段,最后是我正在呈现的表单。
getAndFormatNewReviewForm(event) {
event.preventDefault();
const newReviewForm = document.getElementById('new-review-form')
const submitButton = document.createElement("button")
submitButton.innerHTML = "Add"
submitButton.id = "review-submit"
submitButton.type = "submit"
const buttonDiv = document.getElementById("buttons")
buttonDiv.appendChild(submitButton)
submitButton.addEventListener('click', this.submitReviewInputs.bind(this))
}
最佳答案
我通常不建议这样做,但可能在某个地方异步脚本不按预期顺序运行,或者脚本标签未按预期顺序加载。无论哪种方式,您正在调用的函数都会在 div 元素可用之前调用。一种方法是在合理的时间范围内进行轮询,然后在元素可用后执行您的函数。例如:
function getButton(){
let poll = (res)=>{
let div = document.getElementById("buttons");
if (div) {
res(div);
} else {
window.requestAnimationFrame(function(){poll(res);});
}
};
return new Promise(function(res){poll(res);})
}
使用你会
getButton()
.then(function(div){
el.addEvenlistener("click",getAndFormatNewReviewForm,false);
})
div
是“按钮”,el 是您附加到的 getAndFormatNewReviewForm
的任何内容。将“点击”更改为您想要的任何事件。
请注意,这是一个鸭磁带解决方案,您还需要设计脚本以在必要时终止。
关于javascript - 元素函数appendchild is null错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61295525/