First, the original demand
In the actual project, encountered a problem, is through the JS dynamically generated elements, can not trigger the JS event.
The original JS code:
$ (function () { $ (". Original"). Click (function () { alert ("123"); }); )
The above type of JS code is no problem in handling DOM elements loaded with the page loading. However, after processing the page load, adding the elements on the fly is not valid, and you need to take advantage of the jquery bindings.
Add the JS code of the element dynamically:
$ (function () { $ (". Run"). Click (function () { var BTN = "<button class= ' original ' > I am new to </button>"; $ (". Out"). Append (BTN); }); })
In this case, if you click on the newly added button, the response event cannot be handled by the above declarative formula.
PS: I'm not sure what the reason is.
Second, the on method of jquery
By reviewing the instructions, it is found that the on () method of jquery is to support the binding of events on dynamically added elements, as shown in the following:
Official website Description (English): API explanation
英文说明 (English): Chinese API explanation (recommended)
Please refer to the above website for detailed instructions, here are only a few points to explain:
- Usage format: Jqueryobject.on (events [, selector] [, data], handler)---[This is optional]
- Explanation: Events is a single or multiple event, handler is the action to be performed to trigger the event.
- For selector, if it is null or not, then the element to which the binding jqueryobject matches, and if not NULL, is the binding of all elements in the jquyerobject background element that meet the selector requirements.
Iii. Methods of Treatment
<script type= "Text/javascript" > $ (function () { // Method 1 function () { alert ("HHHH"); }); // not valid? function () { alert ("HHHH"); }); }) </script>
Method 1 certainly works, but it's strange that method 2 is invalid ...
Iv. Supplementary
Think good to add, left to this ...
jquery Dynamic Binding