The bound event for a DOM element that is loaded asynchronously must be bound after the load is complete:
$ (' body '). Load (' learnclickbinding.ashx ');
$ (' a '). Click (function () {alert (' I was clicked! ');});
The above binding is invalid because asynchronous loading takes time, and $ (' a ') is already executed before the element is fetched. Click (); method, so the binding fails.
The right thing to do is to wait for the element to finish loading and then execute $ (' a '). Click ();
$ (' body '). Load (' Learnclickbinding.ashx ', function () {$ (' a '). Click (function () {alert (' I was clicked! ');});
});
JS for DOM element binding events can only be valid until the page is refreshed, that is, before the DOM element is reloaded. This problem is especially true when loading DOM elements asynchronously.
$ (' body '). Load (' Learnclickbinding.ashx ', function () {$ (' a '). Click (function () {alert (' I was clicked! ');}); $ (' body '). empty (); $ ("<a href= ' # ' >click me!</a>"). AppendTo (' body ');});
This binding is also a failure because the a element of the binding event has been empty, and the A element behind append is no event, so the click button still has no effect.
The correct binding method:
$ (' body '). Load (' Learnclickbinding.ashx ', function () {$ (' a '). Click (function () {alert (' I was clicked! ');}); $ (' body '). empty (); $ ("<a href= ' # ' >click me!</a>"). AppendTo (' body '), $ (' a '). Click (function () {alert (' I was clicked! ');});
JS for DOM element binding event notes