3

我有这段代码在测试页面中运行良好......

Javascript:

function myFunction() {
    var x = document.getElementById("tarea"),
        nameInput = document.getElementById('name'),
        classInput = document.getElementById('class');

    var lines = x.value.split('\n');
    var name = lines[0].substring(5);
    var grade = lines[1].substring(6);

    nameInput.value = name;
    classInput.value = grade;
}

HTML:

<textarea rows="4" cols="50" id="tarea" onblur="myFunction()"></textarea>

现在我想使用 Greasemonkey将onblur功能添加到预先存在的页面中。

但是,我不知道如何onblur在 Greasemonkey 中使用 Javascript 事件。我已经搜索但找不到任何使用onblur.

4

1 回答 1

4

使用addEventListener()(纯 javascript)或jQuery.on()(更强大的方法)。

纯JS:

// ==UserScript==
// @name     _YOUR_SCRIPT_NAME
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/

var targInput = document.getElementById ("tarea");
targInput.addEventListener ("blur", myFunction, false);

function myFunction () {
    ... ...
}


jQuery(推荐),注意@require

// ==UserScript==
// @name     _YOUR_SCRIPT_NAME
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/

$(document).on ("blur", "#tarea", myFunction);

function myFunction () {
    ... ...
}
于 2012-12-19T06:59:40.220 回答