[英]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.