繁体   English   中英

从先前的代码更新DOM后,运行javascript代码

[英]Running javascript code after DOM has been updated from previous code

我要输入一个Google新闻提要,然后尝试通过访问新创建的DOM元素来删除某些格式错误的内容。

var aryClassElements = document.getElementById('google-news').getElementsByTagName('div');
alert("Found "+aryClassElements.length+" divs in Google News");

但是此警报显示为0。尚未找到新创建的DOM元素。 阿克!

如果我在加载Google新闻提要和向dom请求google-news中的div元素之间添加无关紧要的警报(“ hello world”),它将找到20个div元素。 我假定用户单击“确定”的响应时间可以使DOM更新。

是否有一些普通的javascript(不是jquery)可以完成相同的结果?

Tx!

如果google-news提供了回调挂钩或伪事件,则可以附加函数以使用它们。 如今,大多数javascript API都有它们。 因此,我的第一个建议是阅读文档。

如果不是,则可以使用setTimeout进行轮询,每秒说一次,并在找到时执行您的函数:

function pollDOM () {
    var aryClassElements =
            document.
                getElementById('google-news').
                getElementsByTagName('div');

    if (aryClassElements.length) {
       // do stuff here;
    }
    else {
        setTimeout(pollDOM,1000);
    }
}
pollDOM();

使用setTimeout创建人为延迟。 更好的方法是使用ajax加载内容,在ajax完成后,设置新的html,然后尝试查找DOM元素。

要加载提要,我正在使用:

feed = new google.feeds.Feed(url);
feed.load(function(result) { [the function to add DOM elements here] }
[the function to read DOM elements here]

我只需要重组一下:

feed = new google.feeds.Feed(url);
feed.load(function(result) { 
  [the function to add DOM elements here]
  [the function to read DOM elements here]
}

一切都很好! 新秀错误,谢谢你们指出我正确的方向。

暂无
暂无

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

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