为什么下面的jquery代码在tampermonkey中不起作用

why the following jquery code does not work in tampermonkey

本文关键字:tampermonkey 不起作用 代码 jquery 为什么      更新时间:2023-09-26

我有以下代码片段要由Tampermonkey在网站上的chrome中执行http://www.thefreedictionary.com/abnormally

我在页面中尝试了它的独立版本,它可以工作,但它不能通过Tampermonkey工作。

代码如下:

// ==UserScript==
// @name       linkify span href
// @namespace  http://use.i.E.your.homepage/
// @version    0.1
// @description  enter something useful
// @match      http://www.thefreedictionary.com/*
// @require    http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js
// @copyright  2012+, You
// @grant      GM_log
// ==/UserScript==
//alert("hello");
jQuery(document).ready (Greasemonkey_main);
function Greasemonkey_main ()
{  
   alert("hjello");
   jQuery("span.hvr").each(function () { jQuery(this).wrap('<a href="/' + jQuery(this).text() + '" style="text-decoration:none;color:inherit" target="_blank"></a>')})
}

为了检查,我还放了一个警报,警报有效,但jquery没有一行代码。

不知道为什么。请帮忙。

注意:

这一行代码的作用是什么?

它只是用一个锚标记来包装页面中的每个span标记。

如何在该页面中试用该代码?

添加jQuery链接的脚本标记,然后从控制台执行这一行,它就可以工作了。

问题是span.hvr链接是动态生成的:当页面加载时,它们并不存在,但稍后脚本会生成它们。

因此,为了让脚本工作,它应该先等待span.hvr元素出现,然后再做任何进一步的操作。

以下修改后的脚本应该可以工作:

// ==UserScript==
// @name       linkify span href
// @namespace  http://use.i.E.your.homepage/
// @version    0.1
// @description  enter something useful
// @match      http://www.thefreedictionary.com/*
// @require    http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js
// @copyright  2012+, You
// @grant      GM_log
// ==/UserScript==
//alert("hello");
jQuery(document).ready(Greasemonkey_main);
function Greasemonkey_main ()
{  
    var isReady = jQuery("span.hvr").length > 0;
    if (!isReady) {
        setTimeout(Greasemonkey_main, 500);
        return;
    }
    jQuery("span.hvr").each(function () {         
        jQuery(this).wrap('<a href="/' + jQuery(this).text() + '" style="text-decoration:none;color:inherit" target="_blank"></a>')
    });
}

如果有些页面中可能没有span.hvr元素,那么您应该让脚本更智能一点——例如,在5-10秒后停止重试。