使用jQuery和userscript更改表数据值

时间:2013-10-24 11:01:33

标签: jquery html google-chrome userscripts tampermonkey

我正在尝试使用jQuery和userscript更改表数据值,但它不起作用。这是我的代码:

// ==UserScript==
// @name       My Fancy New Userscript
// @namespace  http://use.i.E.your.homepage/
// @version    0.1
// @description  enter something useful
// @copyright  2012+, You
// ==/UserScript==


// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
  var script = document.createElement("script");
  script.setAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js");
  script.addEventListener('load', function() {
    var script = document.createElement("script");
    script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();";
    document.body.appendChild(script);
  }, false);
  document.body.appendChild(script);
}

// the guts of this userscript
function main() {
  // Note, jQ replaces $ to avoid conflicts.
 $('.last').html('111');
}

// load jQuery and execute the main function
addJQuery(main);

我做错了什么?我在Chrome 30.0.1599.69上使用Tampermonkey扩展程序

1 个答案:

答案 0 :(得分:1)

该代码的立即错误是$('.last').html('111');需要JQ('.last').html('111');

addJQuery()JQ内定义$,而不是main(),这不是addJQuery()的最佳版本。


但是,更大的问题是这不是在Tampermonkey(或Greasemonkey)上使用jQuery 的明智方法。尽可能将脚本与页面代码隔离开来。

您的整个脚本应该是:

// ==UserScript==
// @name     _YOUR_SCRIPT_NAME
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @version  0.1
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
$('.last').html ('111');


请务必将@include指令与目标网页匹配。