Home > Web Front-end > JS Tutorial > body text

How to bind events to dynamically added html elements

不言
Release: 2018-07-07 10:47:18
Original
2307 people have browsed it

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)
})
Copy after login

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:

web printing function

##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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!