This is done by my userscript on page load:

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

The web app the userscript targets, adds new $('a.people') elements when the user does various actions.

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?

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:

(Note that the older Mutation events are deprecated and not the same as mutation observers.)

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.

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);
}

其他提示

you need to use jquery on() for dynamicly added elements

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top