我正在编写一个脚本,用于更改我经常使用的网站的消息系统。它在每个消息线程的顶部添加一个按钮。单击时,它会自动移动到主题中的最新消息。
我遇到的问题是消息是由php加载的,并且在加载消息之前脚本会触发。该站点也不会同时加载所有消息线程。它会加载10个左右,然后向下滚动它会加载更多。有没有办法让每个消息线程加载按钮,或者我是否为无法达到目标而拍摄?
// ==UserScript==
// @name Imgur - Message Viewer
// @namespace Basion
// @description It skips to the bottom of the most recent message
// @author Basion
// @include http://imgur.com/*
// @include https://imgur.com/*
// @include http://*.imgur.com/*
// @include https://*.imgur.com/*
// @run-at document-end
// ==/UserScript==
var messages = document.getElementsByClassName("thread-wrapper");
var newA = document.createElement('a');
for (var i = 0; i < messages.length; i++) {
newA.addEventListener("click", scrollToMessage(i), true);
newA.innerText = "Go to Newest Message";
messages[i].appendChild(newA);
}
function scrollToMessage(id) {
var newMessages = document.getElementsByClassName('thread-wrapper');
newMessages[id].scrollIntoView(false);
}
答案 0 :(得分:1)
要处理通过AJAX添加的元素,请使用jQuery和waitForKeyElements
,如"Run Greasemonkey script on the same page, multiple times?"所示。
这是a handy jQuery reference。
此外,您不能以这种方式向事件侦听器发送id。
这是一个完整的工作,后跳转脚本,适用于问题的代码和Imgur目标页面:
// ==UserScript==
// @name Imgur - Message Viewer
// @namespace Basion
// @description It skips to the bottom of the most recent message
// @author Basion
// @include http://imgur.com/*
// @include https://imgur.com/*
// @include http://*.imgur.com/*
// @include https://*.imgur.com/*
// @run-at document-end
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
waitForKeyElements ("div.thread-wrapper", addJumpButton);
/*-- Prepend a button to the top of each thread. Don't add in the header, to
avoid conflicts with the open/close toggle.
*/
function addJumpButton (jNode) {
jNode.prepend (
'<a href="#" class="gmThreadJmpBtn">Go to Newest Message in thread</a>'
);
}
//-- Activate *all* the jump buttons with one jQuery function.
$("div.notifications").on (
"click", "div.thread-wrapper a.gmThreadJmpBtn", jumpToEndOfThread
);
function jumpToEndOfThread (zEvent) {
//-- The last (newest) message will be just above the "reply bar".
var thisThreadHdr = $(zEvent.target);
var targetDiv = thisThreadHdr.nextAll ("div.reply.striped");
targetDiv[0].scrollIntoView (false);
//-- Block the page handlers from also firing for this link.
zEvent.stopPropagation ();
zEvent.preventDefault ();
}