1

我正在编写一个脚本来更改我经常使用的网站的消息系统。它在每个消息线程的顶部添加一个按钮。单击时,它会自动移动到线程中的最新消息。

我遇到的问题是消息是由 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);
}
4

1 回答 1

1

要处理通过 AJAX 添加的元素,请使用jQuerywaitForKeyElements“在同一页面上多次运行 Greasemonkey 脚本?”中所示。.
这是一个方便的 jQuery 参考

此外,您不能以这种方式将 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 ();
}
于 2013-05-27T13:57:34.167 回答