How to register a javascript event handler for an element that has not yet been added to the page

I am trying to create a greasemonkey script that will dynamically create data tables based on user interaction ... other dynamically created data tables. My problem is that I have to do two passes each time I create a table: one to create the table, and the other to capture all the objects in the table. I want to add event handlers (by id) and add various event handlers for them.

If I try to, say, add an onClick event to the td table before I create the table and paste it into the HTML, I get a component unavailable exception.

This is incredibly cumbersome because I either have to keep a list of identifiers separately, and what should I do with these elements when I do my second pass to add handlers or develop a naming convention that I know based on id that I should do with the item.

There must be a better way to do this. I have not figured this out yet. Does anyone have any idea?

+3
source share
4 answers

-, , TD. , ​​ ? TD . , , DOM, ! DOM, .

jQuery live() , , , , , . . body, , , TD doSomething() →

document.body.onclick = function(e) {

    var realTarget = e ? e.target : window.event.srcElement;

    if ( realTarget.nodeName.toLowerCase() === 'td' ) {
        doSomething();
    }

};

-, ( "propogation" ), , . , , DOM, . , , 'click', 'click' .. ..

+11

jQuery 1.3+ live(), , .

+5

, , .

" , ".

, , ( ), , . , Jquery .

+1

JimmyP, event bubbling. , - :

capture('click', '#element-id', function(event) {
    // `this` will be the originating element
    // return `false` to prevent default action
});
+1

Source: https://habr.com/ru/post/1704401/


All Articles