简体   繁体   English

Javascript问题 - 使用getElementById间歇性地找不到元素

[英]Javascript issue - intermittently cannot find element using getElementById

I am having a problem with some javascript that I wrote that is only working intermittently. 我遇到一些问题,我写的只是间歇性地工作。 I dont know a huge amount about how things work in the DOM but I suspect that the JS that I have written is trying to access an element in the DOM before it exists. 我不太了解DOM中的工作方式,但我怀疑我编写的JS是在它存在之前尝试访问DOM中的元素。 I wrote the JS to add it to a formassembly form. 我编写了JS来将它添加到formassembly表单中。 I do not have access to the actual code in the form to make changes there, I can only make JS changes. 我无法访问表单中的实际代码来进行更改,我只能进行JS更改。

Here is the link to the form http://www.tfaforms.com/186347 以下是表格http://www.tfaforms.com/186347的链接

and this is the javascript that I am using on document load 这是我在文档加载时使用的javascript

 window.onload=function() {

document.getElementById("submit-").style.visibility = "hidden";
document.getElementById("wfPageNextId1").value="Calculate";
document.getElementById('wfPageNextId1').setAttribute('onclick', 'Calculate2011()')

}

I am getting errors saying that wfPageNextId1 is null and setAttribute cannot be called. 我收到错误,说wfPageNextId1为null并且无法调用setAttribute。

Any help would be very much appreciated. 任何帮助将非常感谢。 Thanks in advance. 提前致谢。

It looks like some of the DOM is getting created dynamically by other scripts. 看起来有些DOM是由其他脚本动态创建的。 You can delay until the elements exist via something along these lines: 您可以通过以下方式延迟元素存在:

function initializeForm() {
   var submit = document.getElementById("submit-"),
       nextPage = document.getElementById("wfPageNextId1");
   if (submit && nextPage) {
      submit.style.visibility = "hidden";
      nextPage.value = "Calculate";
      nextPage.setAttribute('onclick', 'Calculate2011()');
   } else {
      // try again in 1 second
      setTimeout(initializeForm, 1000);
   }
}

window.onload = function() {
   initializeForm();
};

You should also make sure you are not nuking any window.onload defined in the other scripts: 您还应该确保您没有查看其他脚本中定义的任何window.onload

if (window.onload) {
   var currentOnload = window.onload;
   window.onload = function() { currentOnload(); initializeForm(); };
} else {
   window.onload = function() { initializeForm(); };
}

Checked the page HTML and infact there is no HTML element with the id wfPageNextId1. 检查页面HTML并且实际上没有id为wfPageNextId1的HTML元素。 What is the element on the page that you are trying to access? 您尝试访问的页面上的元素是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM