可以在JavaScript中保存对尚未存在的elment的引用吗? [英] Is it possible to save a reference to a not yet existing elment in JavaScript?

查看:107
本文介绍了可以在JavaScript中保存对尚未存在的elment的引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前曾尝试提过这个问题,但很难解释。所以这里我要尝试改写它。

I have attempted to asked this question before, but it's quite difficult to explain. So here I'm going to try to rephrase it.

这是我的HTML主体:

This is my HTML body:

<bod>
<div id="foo"></div>
<div id="bar"></div>
</body>

在JavaScript中,我调用一个引用节点作为参数的函数。其中一些存在,有些不存在。

In JavaScript I'm calling a function with references to nodes as arguments. Some of them exists, some don't.

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 时,已经创建了和引用,因为它们在window.list中为null。
有什么办法可以保存对尚未创建的元素的引用。我不能使用class,id等,因为我正在动态地创建这些元素。

The problem, that I'm having is that when I call the variable window.list after peaches and oranges have been created, that they are not referenced because they are null in window.list. Is there any way I can save a reference to elements that have not yet been created. I can't use class, id, etc., because I am creating these elements dynamically.

谢谢!

推荐答案


有没有办法保存对尚未创建的元素的引用。

Is there any way I can save a reference to elements that have not yet been created.

否。但是请看下面。


我不能使用类,id等,因为我正在动态创建这些元素。

I can't use class, id, etc., because I am creating these elements dynamically.

使用 id s

最好的做法是只需要创建元素的代码,然后使用已创建的元素调用该函数。如果由于某种原因您无法做到这一点,基本上还有其他的一种解决方法。

The best thing to do is simply to have the code that creates the elements then call the function with the elements that have been created. Anything else is basically a workaround if for some reason you can't do that.

一种这样的解决方法是轮询:您设置了一个定时器来检查。 >

One such workaround is polling: You set up a timer to check back.

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

这将继续寻找元素,直到找到它们。

That will keep trying to find the elements until it's found them all.

这篇关于可以在JavaScript中保存对尚未存在的elment的引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆