This article mainly introduces the method of binding events to dynamically added html elements. It has certain reference value. Now I share it with everyone. Friends in need can refer to it.
Avoid writing DOM first operation, but the element is loaded dynamically, so clicking does not take effect. There are two better methods:
1. Add inline events when adding dynamically, such as onclick="funcName()"
Just write the method corresponding to the method name in js. If there are too many elements to bind the method, you can consider using method two;
2. jquery’s on event binding
eg:
on事件可以给动态添加的元素也绑定事件。 $("#optionGroup").on('click','.input-group .delete-option',function () { console.log("aaa") let num = $(this).parents(".input-group").index(); console.log(num) })
Note: The on event first obtains the parent element and then binds it to the child element. It is best for the parent element to be an existing element rather than dynamic Additional.
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
##Vue Electron implements simple desktop application
The above is the detailed content of How to bind events to dynamically added html elements. For more information, please follow other related articles on the PHP Chinese website!