我在http://www.thefreedictionary.com/abnormally网站上有以下代码段,这些代码将由Tampermonkey以chrome格式执行
我在页面中尝试了它的独立性,它可以工作,但不能通过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秒后停止重试。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句