JQuery adding row to table with click () handler for tr

I have a problem with the control that I create that contains a table where the body scrolls. Lines have a click () function handler, for example:

    /**
     * This function is called when the user clicks the mouse on a row in
     * our scrolling table.
     */
    $('.innerTable tr').click (function (e) {
      //
      // Only react to the click if the mouse was clicked in the DIV or
      // the TD.
      //
      if (event.target.nodeName == 'DIV'  ||
          event.target.nodeName == 'TD'     ) {
        //
        // If the user wasn't holding down the control key, then deselect
        // any previously selected columns.
        //
        if (e.ctrlKey == false) {
          $('.innerTable tr').removeClass ('selected');
        }

        //
        // Toggle the selected state of the row that was clicked.
        //
        $(this).toggleClass ('selected');
      }
    });

There is a button that adds rows to the table, for example:

$('#innerTable > tbody:last').append('<tr>...some information...</tr>');

While the ARE lines have been successfully added, for some reason, the static lines work with the click handler, but not in the new lines added. Is something missing?

+3
source share
1 answer

Try to use . live () :

$('.innerTable tr').live('click', function (e) { ... });

It will bind the event handler to any current and future elements matching the selector added to the DOM.

+3
source

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


All Articles