我以前曾尝试问过这个问题,但很难解释。所以在这里我将尝试重新表述它。
这是我的 HTML 正文:
<bod>
<div id="foo"></div>
<div id="bar"></div>
</body>
在 JavaScript 中,我调用一个函数,并将节点引用作为参数。其中一些存在,一些不存在。
myElements([document.getElmentById('foo'), document.getElmentById('bar'), document.getElmentById('peaches'), document.getElmentById('oranges')]);
//foo and bar exist, peaches and oranges don't
function myElements(list){
window.list = list; //list returns [element], [element], null, null
}
我遇到的问题是当我调用变量 window.list 时after peaches and oranges已创建,但它们未被引用,因为它们在 window.list 中为 null。
有什么方法可以保存对尚未创建的元素的引用。我can't使用类、id 等,因为我正在动态创建这些元素。
Thanks!
有什么方法可以保存对尚未创建的元素的引用。
不,但请参阅下文。
我无法使用 class、id 等,因为我正在动态创建这些元素。
You are using id
s.
最好的办法就是让代码创建元素,然后使用已创建的元素调用函数。如果由于某种原因你无法做到这一点,其他任何方法基本上都是一种解决方法。
其中一种解决方法是轮询:您设置一个计时器来检查。
myElements(['foo', 'bar', 'peaches', 'oranges']);
function myElements(list){
window.list = list;
findElements();
function findElements() {
var n, element, entry, repeat = false;
for (n = 0; n < window.list.length; ++n) {
entry = window.list[n];
if (typeof entry === "string") {
element = document.getElementById(entry);
if (element) {
window.list[n] = element;
}
else {
repeat = true;
}
}
}
if (repeat) {
setTimeout(findElements, 50); // Do it again, 50ms later
}
}
}
它将继续尝试寻找元素,直到找到所有元素。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)