在处理一些旧代码 atm 时,我在使用 Javascript
和 Internet Explorer 时遇到了一个非常烦人的问题。
GUI 的设置由使用 document.write()(来自 .js 文件)打印的几行 HTML 以及 Javascript 函数内部的一些工作组成。
在 Javascript 函数中,DOM 似乎没有完全加载,因为像 this.domInputObj.setAttribute(a,b)
这样的简单语句会产生 setAttribute
错误> 调用了无效元素。
A.js
//Some where in the beginning we print an input field with document.write
document.write('<input ...');
...
new SomeObject(document.forms[formA].inputFieldA)
B.js
function SomeObject(inputFieldObj) {
// the text input field
this.inputObjFieldObj = inputFieldObj;
this.inputFieldObj.setAttribute('a','b') //e.g. yields error in IE
}
我的问题是如何仅在 IE 中发生这种情况?我认为这与 .js 文件的加载顺序有关(可能仍然如此),并且其他浏览器“更智能”?
如果我调试,那么 document.write
会在 Javascript 调用之前发生,但它是否以某种方式进行缓冲?
非常感谢您的任何想法。
编辑
澄清了 B.js。此外,字母命名并不意味着加载顺序。
最佳答案
根据我的经验,当您尝试动态创建元素(例如)时,这通常发生在 IE 6/7 中。与您的document.write('<input ...')
语句,然后使用 setAttribute
对其进行操作/样式设置而不仅仅是操纵物体。旧版本的 IE 不会更新 DOM 和其他内部属性来识别这些动态元素已添加,因此会出现错误。
我会尝试这个,例如:
var input = document.createElement('input');
// Add a CSS class to it
input.className = "yourClass";
// Add a CSS rule to it
input.style.color = "#FF0000";
而不是
document.write('<input type="text" id="input1" />');
document.getElementById('input1').setAttribute('class','yourClass');
document.getElementById('input1').setAttribute('color','#FF0000');
关于javascript - 从 Javascript 函数加载和引用 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16588696/