Method for jQuery to dynamically append events to DOM

  • 2021-07-21 07:18:19
  • OfStack

Handle a list binding, because it is a display project, without using complex plug-ins, jsrender directly wrote a template, but there is an operation button behind it to view the data details, thought of jquery using on for event delegation, and then started

It was originally written like this:


$(".btn-open").on("click", function () {        
alert($(this).text());      
})

Of course, this doesn't work, because after document reday, the element. btn-open doesn't exist at all, the list is not bound, and events certainly don't help!

Then there is this:


$(".table").on("click", ".btn-open", function () {        
alert($(this).text());      
})

The code can be seen clearly. Find the. table element and append the click event to. btn-open. Generally speaking, this is enough. But it still doesn't work. I'm sorry. I'm beginning to doubt my memory. Then I went to find the next document.

The document says:

Event handling can only be bound to the currently selected element; Also, by the time your code calls. on (), they must already exist in the page document.

Well, in document ready,. table does not exist, so we will continue to change it


$(document).on("click", ".btn-open", function () {        
alert($(this).text());      
})

I can finally work.

Summary:

1. Differences between jQuery delegate events and directly bound events:

$("X"). on ("click", function () {})

$("X"). on ("click", "Select child elements of X", function () {})

2. Event handlers can only be bound to elements that currently exist, meaning that the contents of the first selector must currently exist (which is why code 2 doesn't work because. table doesn't exist), so to be on the safe side, you can bind delegate events directly to document.

I didn't read the document carefully before, and I was ambiguous about this piece. Today, I made it clear and recorded it.


Related articles: