Modify new elements when they are added

可紊 提交于 2019-12-02 21:28:06

问题


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.


回答1:


If you want to act on new elements when the target page adds them, you have two choices:

  • MutationObserver
    or
  • Polling

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



回答2:


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



来源:https://stackoverflow.com/questions/23321566/modify-new-elements-when-they-are-added

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!