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