[英]My Greasemonkey script is not finding the elements (links) on the page?
该网站是: lexin.nada.kth.se/lexin/#searchinfo=both,swe_gre,hej;
我的脚本是:
function main(){
var links=document.getElementsByTagName("a");
alert("There are " + links.length + "links.");
}
main();
运行脚本会给我两条警告消息,提示
有0个链接。
为什么我无法从文档中获得正确数量的链接? 为什么我会两次收到警报?
警报触发不止一次,因为该页面包含iFrame(事实上,该URL与主页相同)。 Greasemonkey将iFrame视为独立的网页。 使用@noframes
停止该操作。
该脚本未找到链接,因为在页面加载和GM脚本启动后很长一段时间内,它们是通过javascript添加的。 这是脚本和AJAX的常见问题。 一个简单,可靠的解决方案是使用waitForKeyElements()
(和jQuery)。
以下是一个完整的示例脚本 ,该脚本避免使用iFrame,并显示了如何获取动态链接:
// ==UserScript==
// @name _Find elements added by AJAX
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @match http://stackoverflow.com/questions/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @noframes
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
var totalUsrLinks = 0;
waitForKeyElements ("a[href*='/users/']", listLinks);
function listLinks (jNode) {
var usrMtch = jNode.attr ("href").match (/^.*\/users\/(\d+)\/.*$/);
if (usrMtch && usrMtch.length > 1) {
totalUsrLinks++;
var usrId = usrMtch[1];
console.log ("Found link for user: ", usrId, "Total links = ", totalUsrLinks);
}
}
由于.getElementsByTagName
而返回HTMLcollection,因此,您必须使用.getElementsByTagName
声明HTMLcollection,然后找到长度并发出警报。 看起来像这样...
(function main(){ var links = document.getElementsByTagName("a").length alert("There are "+ links + " links."); })()
我在这里在IIFE上添加了IIFE或立即调用函数表达式,因此您不必调用该函数,因此代码很小,可以被“吞噬”。 最后,它正在警告2个警告框,因为该函数中有一个[alert box],而您正在调用该函数,因此它将执行相同的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.