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

标签 javascript jquery

所以我想做的是使用 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/

关于javascript - 脚本在第一次运行后停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16290039/

相关文章:

javascript - 使用 JXA 访问对象的属性

jquery - 该网站使用了哪种效果?

jquery - 如何通过类名添加点击事件?

javascript - 在 JS 执行之前应用 CSS 字体

javascript - 不会改变整个站点高度的可滚动子内容

javascript - preventDefault() 不会阻止该操作

javascript - Android转义JavaScript字符串

JavaScript - 使用 .map 时将第二个参数传递给 ES6 模板

jquery - jquery 上的 IE7 链接问题

javascript - 有没有比使用 jQuery 的 each 更好的搜索 JavaScript 数组的方法?