gpt4 book ai didi

javascript - Greasemonkey与jQuery,如何编写greasemonkey脚本来修改页面DOM元素?

转载 作者:行者123 更新时间:2023-11-28 21:17:08 25 4
gpt4 key购买 nike

从greasemonkey wiki 页面,有一个使用jQuery 和greasemonkey 的示例。下面列出了代码,页面位置为http://wiki.greasespot.net/Third-Party_Libraries#jQuery

// ==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 函数 包围代码,如下所示:

// ==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代码没有在每次刷新页面时执行。关于这个问题有什么想法吗?谢谢。

最佳答案

不,将脚本代码包装在 jQuery() 调用中,或者使用 $(document).ready () 都是没有意义的。

Greasemonkey 在 DOMContentLoaded 事件(与 jQuery 包装器或就绪事件相同)之后以及加载 GM 版本的 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!');
    }
    }
    }

关于javascript - Greasemonkey与jQuery,如何编写greasemonkey脚本来修改页面DOM元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7283923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com