我有两种方法,可以在几页中很好地工作,但是当谈到Greasemonkey脚本时,它们由于某种原因而失败,并抛出“不是函数”错误。
正常情况下,将相同的代码正常附加到页面上即可。

HTMLTableRowElement.prototype.hideRow = function(){this.style.display = 'none'};
HTMLTableRowElement.prototype.showRow = function(){this.style.display = ''};


调用这些功能之一时出现错误。有什么线索吗?

最佳答案

该代码在Greasemonkey脚本中不起作用,因为GM脚本位于不同的范围内,并且(名义上)位于沙箱中。有关更多信息和解决方法,请参见"Why is window (and unsafeWindow) not the same from a userscript as from a script tag"(可能是@grant none,或者是脚本注入,或者是unsafeWindow)。

但是,除非您试图更改由页面添加到页面的现有代码,否则请不要那样做。

使用jQuery的.hide().show().toggle()


或使用GM_addStyle(),EG创建一个类:

GM_addStyle (".GM_hide {display: none !important;}");


并使用DOM函数根据需要添加或删除类。例如:

//--- Select the 2nd row of the first table
var someRow = document.querySelector ("table tr:nth-of-type(2)");

someRow.classList.add    ("GM_hide");
someRow.classList.remove ("GM_hide");
someRow.classList.toggle ("GM_hide");

08-20 00:02