脚本在第一次运行后停止工作

Script stops working after first run

本文关键字:停止工作 运行 第一次 脚本      更新时间:2023-09-26

所以我要做的是使用Greasemonkey更改表中丢失列中的数据。

我遇到的问题是,该网站的导航栏(共3个链接)使用JavaScript加载新页面(即URL不改变),如果你去一个不同的页面,但然后回来,我已经做的任何和所有的改变都丢失了(因为代码不会再次运行),只有刷新修复它。使用waitForKeyElements()工作在第一个页面加载,但它停止工作之后。为了测试它,我将.click加入.a.p。点击第一个链接滑动它(即工作正常),但它停止工作之后。.p部分也一样。我必须把整个东西都循环起来吗?或者我应该设置一个计时器,每隔x秒执行一次脚本。

目前为止的代码

// ==UserScript==
// @name        changetext
// @namespace   changetext
// @include     *
// @version     1
// @grant       none
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js
// @require     https://gist.github.com/raw/2625891/waitForKeyElements.js
// ==/UserScript==

$('p').click(function () {
    $(this).slideUp();
});
$('a').click(function () {
    $(this).slideUp();
});
waitForKeyElements ("#row", newdata());
function newdata()
{
    document.getElementById("row").innerHTML = "<span class='text'>Test</span>";
}

查看waitForKeyElements.js的源代码:

function waitForKeyElements (
    selectorTxt,    /* Required: The jQuery selector string that
                        specifies the desired element(s).
                    */
    actionFunction, /* Required: The code to run when elements are
                        found. It is passed a jNode to the matched
                        element.
                    */
    bWaitOnce,      /* Optional: If false, will continue to scan for
                        new elements even after the first match is
                        found.
                    */
    iframeSelector  /* Optional: If set, identifies the iframe to
                        search.
                    */
) { ... }

actionFunction的描述强烈建议你应该传递给它一个函数,而不是函数执行的结果。"当…时运行的代码".

// GOOD - pass the function itself to serve as a callback
waitForKeyElements ("#row", newdata);
// BAD - calls the function once and passes the result (if any) of 
// executing the function
waitForKeyElements ("#row", newdata());

你也可以这样写:

waitForKeyElements ("#row", function() {
        document.getElementById("row").innerHTML = "<span class='text'>Test</span>";
    });

进一步看,我认为你的选择器也有问题。脚本应该在添加新元素时触发与指定选择器匹配的新元素。然而,你有一个ID选择器,每个文档只能有一个ID。

试试下面这个使用类名的脚本:http://jsfiddle.net/Lh438/