添加新元素时对其进行修改 [英] Modify new elements when they are added
问题描述
这是由我的用户脚本在页面加载时完成的:
This is done by my userscript on page load:
$('a.people').each(function (index, value) {
$('<i>'+$(value).text()+'</i>').insertBefore(value);
});
用户脚本所针对的Web应用程序在用户执行各种操作时添加新的$('a.people')
元素.
The web app the userscript targets, adds new $('a.people')
elements when the user does various actions.
如何为新添加的元素运行代码?将新元素添加到DOM时是否会触发事件?
How can I run my code for the newly added elements? Is there an event which is triggered when new elements are added to the DOM?
我不想使用setInterval
,因为代码会在不需要时循环并影响性能.
I don't want to use setInterval
because the code will loop when not required and affect the performance.
推荐答案
如果要在目标页面添加新元素时对其进行操作,则有两种选择:
If you want to act on new elements when the target page adds them, you have two choices:
- MutationObserver
或 - 投票
- MutationObserver
or - Polling
(请注意,较早的Mutation事件已弃用,并且与突变观察者不同.)
(Note that the older Mutation events are deprecated and not the same as mutation observers.)
此外,您需要跟踪已完成的节点,并避免重复修改它们.有一个实用程序: waitForKeyElements .它使用轮询并处理所有开销.您不会注意到页面变慢.
In addition, you'll need to track which nodes have been done and avoid repeatedly modifying them. There is a utility for this: waitForKeyElements. It uses polling and handles all the overhead. You will not notice a page slowdown.
一个适用于Greasemonkey或Tampermonkey的完整用户脚本,它将使用waitForKeyElements
替换您的问题代码,
A complete userscript, suitable for Greasemonkey or Tampermonkey, that replaces your question code, using waitForKeyElements
would be:
// ==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);
}
这篇关于添加新元素时对其进行修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!