【问题标题】:JScript Check if element exists and remove itJAVAScript 检查元素是否存在并将其删除
【发布时间】:2014-03-02 17:01:46
【问题描述】:

我正在尝试在 javascript 中编写一个简单的函数来检查一个元素是否存在于 DOM 中,如果它确实删除了,如果没有,将它附加到页面,到目前为止我已经得到了这个

        if document.contains(document.getElementById("submitbutton") {
            document.getElementById("submitbutton").remove();
}   else {
        lastDiv.appendChild(submitButton);  
        }

(lastDiv 只是我想将 div 'submitButton' 附加到的 div) 但是我收到错误“未捕获的 ReferenceError:myFunction 未定义”

有什么帮助吗? 我知道这是一个非常新手的问题,对此感到抱歉

【问题讨论】:

  • 我们需要更多的代码。 myFunction在哪里?
  • 这是一个很长的函数,但这是其中唯一导致错误的部分,我已经调试了其余部分
  • @howdybaby 没有,myFunction有问题
  • 但是当我从函数中删除这些代码行时,它的其余部分运行良好,但是当我添加这些行时,整个事情都中断了

标签: javascript element exists


【解决方案1】:

代码中有语法错误,if 语句需要括号

if (document.contains(document.getElementById("submitbutton"))) {
            document.getElementById("submitbutton").remove();
}   else {
        lastDiv.appendChild(submitButton);  
}

【讨论】:

  • @howdybaby 很高兴我能帮上忙!
  • if (document.contains(document.getElementById("submitbutton")) 应该改为 if (document.contains(document.getElementById("submitbutton"))) 你忘了一个参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-16
  • 2015-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多