【问题标题】:element function appendchild is null error元素函数 appendchild 为空错误
【发布时间】:2020-04-18 20:07:44
【问题描述】:

我目前正在尝试创建一个创建表单的函数,该函数有一个提交按钮,默认情况下是隐藏的,直到从另一个按钮触发。我的按钮当前按我的意愿弹出表单,但在表单中我的添加按钮不存在,我也无法实际添加到表单,因为它说 appendChild 为空。但是检查服务器和查询都表明找到了该值。下面是我的错误,一个特定的 sn-p,最后是我正在呈现的表单。

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))
     } 

【问题讨论】:

  • 你确定你有一个带有id="buttons"的HTML元素吗?
  • 所以你肯定在这里做了一些事情,我能够纠正这个问题,它是 html 中的一个简单的错字,是按钮而不是导致它们出现的按钮。

标签: javascript forms function rendering


【解决方案1】:

我通常不建议这样做,但可能是异步脚本未按预期顺序运行,或者脚本标签未按预期顺序加载。无论哪种方式,您正在调用的函数都会在 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 附加到的任何内容。将“点击”更改为您想要的任何事件。

请注意,这是一种鸭式磁带解决方案,您还需要设计脚本以在必要时终止。

【讨论】:

  • 是的,但我确实知道这对将来使用会有什么帮助,我也很欣赏这个解决方案。
【解决方案2】:

首先你必须从 buttonDiv 常量中获取日志(console.log() 方法),如果不为空,请更改

 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))
     } 

 getAndFormatNewReviewForm(event) {
       event.preventDefault();
       var newReviewForm = document.getElementById('new-review-form')   
       var submitButton = document.createElement("button") 
       submitButton.innerHTML = "Add"
       submitButton.id = "review-submit"
       submitButton.type = "submit"
       var buttonDiv = document.getElementById("buttons")
       buttonDiv.appendChild(submitButton)
       submitButton.addEventListener('click', this.submitReviewInputs.bind(this))
     } 

我认为这会奏效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 2019-07-21
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多