How can I be notified when an element is added to the page?

前端 未结 8 2145
别跟我提以往
别跟我提以往 2020-11-22 16:11

I want a function of my choosing to run when a DOM element is added to the page. This is in the context of a browser extension, so the webpage runs independently of me and I

8条回答
  •  不知归路
    2020-11-22 16:46

    You can use livequery plugin for jQuery. You can provide a selector expression such as:

    $("input[type=button].removeItemButton").livequery(function () {
        $("#statusBar").text('You may now remove items.');
    });
    

    Every time a button of a removeItemButton class is added a message appears in a status bar.

    In terms of efficiency you might want avoid this, but in any case you could leverage the plugin instead of creating your own event handlers.

    Revisited answer

    The answer above was only meant to detect that an item has been added to the DOM through the plugin.

    However, most likely, a jQuery.on() approach would be more appropriate, for example:

    $("#myParentContainer").on('click', '.removeItemButton', function(){
              alert($(this).text() + ' has been removed');
    });
    

    If you have dynamic content that should respond to clicks for example, it's best to bind events to a parent container using jQuery.on.

提交回复
热议问题