簡體   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