添加时修改新元素

时间:2014-04-27 09:20:13

标签: javascript jquery userscripts

这是由我的用户脚本在页面加载时完成的:

$('a.people').each(function (index, value) {
     $('<i>'+$(value).text()+'</i>').insertBefore(value);
});

用户脚本定位的网络应用,在用户执行各种操作时添加新的$('a.people')元素。

如何为新添加的元素运行代码?将新元素添加到DOM时是否会触发事件?

我不想使用setInterval,因为代码会在不需要时循环并影响性能。

2 个答案:

答案 0 :(得分:1)

如果您希望在目标页面添加新元素时对其执行操作,则有两种选择:

(请注意,旧的Mutation事件已被弃用,与变异观察者不同。)

此外,您还需要跟踪已完成的节点,并避免重复修改它们。有一个实用工具:waitForKeyElements。它使用轮询并处理所有开销。你不会注意到页面减速。

适用于Greasemonkey或Tampermonkey的完整用户说明,使用waitForKeyElements替换您的问题代码将是:

// ==UserScript==
// @name     _Italicize People entries
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.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.
*/

waitForKeyElements ("a.people", italicizePeople);

function italicizePeople (jNode) {
    $('<i>' + jNode.text() + '</i>').insertBefore (jNode);
}

答案 1 :(得分:0)

您需要使用 jquery on() 来动态添加元素