2011-09-02 36 views
0

在greasemonkey wiki頁面中,有一個使用jquery和greasemonkey的示例。代碼如下所示,並且頁面的位置是http://wiki.greasespot.net/Third-Party_Libraries#jQuery帶jQuery的Greasemonkey,如何編寫greasemonkey腳本來修改頁面DOM元素?

// ==UserScript== 
// @name   jQuery Example 
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js 
// ==/UserScript== 

// Append some text to the element with id someText using the jQuery library. 
$("#someText").append(" more text."); 

此示例腳本直接修改DOM。我是否需要環繞代碼與jQuery function這樣的:

// ==UserScript== 
// @name   jQuery Example 
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js 
// ==/UserScript== 

// Append some text to the element with id someText using the jQuery library. 
jQuery(function(){ 
    $("#someText").append(" more text."); 
}) 

我問這個問題,是因爲我的Greasemonkey代碼每次頁面刷新時不執行。關於這個問題的任何想法? 謝謝。

+0

有時訪問從Greasemonkey腳本的DOM,你可能需要使用unsafeWindow.jQuery –

+0

當是「有時」? – MarkS

回答

3

不,沒有必要在jQuery()調用中包裝腳本代碼,也不要使用$(document).ready()

Greasemonkey在DOMContentLoaded事件(與jQuery包裝器或就緒事件相同)和加載jquery版本之後自動觸發。

另請注意,該wiki頁已過時。 GM現在可以很好地使用jQuery 1.6.2。

你沒有顯示相關的代碼,也不鏈接目標頁,但「Greasemonkey的代碼是每次頁面刷新時不執行」的最可能的原因是:

  1. GM腳本中有錯誤。

  2. 目標內容通過AJAX單獨加載。
    您可以在此模式中使用的代碼,要解決這個問題:

    //--- This handles both page-load delays, and AJAX changes. 
    setInterval (function() { checkForTweetbox(); }, 500); 
    
    function checkForTweetbox() { 
        var tweetbox = document.querySelector ('div.tweet-box textarea'); 
        if (tweetbox) { 
         if (! tweetbox.weHaveProcessed) { 
          tweetbox.weHaveProcessed = true; 
          alert ('New tweet-box found!'); 
         } 
        } 
    } 
    
+0

#2是有幫助的。這通常是知道元素何時由AJAX調用提供的最佳方式嗎?或者有沒有辦法建立一個回調,它已被插入(vs輪詢)?我仍然認爲自己是一個JavaScript和jQuery的新手,可以在頁面上重新排列一堆HTML,其中一些在頁面加載後加載。 – MarkS

+1

@MarkS輪詢是一種非常強大且易於使用的技術。特別是如果你通過像'waitForKeyElements()'這樣的工具來完成。爲了獲得更好的性能,你可以使用'MutationObs erver's。 –

相關問題