简体   繁体   中英

Dynamic Html elements click event Manage

I am using plan Javascript to manage my code, I have certain elements which are appended after certain actions has been performed. I want to trigger click event on those elements, predefining click event by classname is not working as JS gets loaded and DOM elements are updated later on.

SO to avoid that I have used this to solve the problem

document.body.addEventListener('click', event => {
      if (event.target.className == 'close-image') {
          //certain operations
      }
}

But this isn't ideal solution, because everytime input buttons are pressed it goes out checking className, so any alternative to use this?

I am not using jquery else I would have managed it

First of all, it's not a bad solution, it's called the event delegation technique, and it's ok to check the class name each time you fire an event.

Another solution is adding the event while you create the element, so if you are using createElement method, you can just add event listener after getting the element referance.

const button = document.createElement('button')
button.addEventListener('click', () => {
  // some code.
})

Or if you are using the insert HTML methods, you can use event attributes like onclick .

This is called event delegation . The performance impact is not really an issue . I would advice to use evt.target.classList.contains(...) though.

 document.addEventListener(`click`, handle); // create a few buttons for (let i = 0; i < 5; i += 1) { document.body.append( Object.assign( document.createElement(`button`), {className: `close-image`, textContent: `button ${i + 1}`, id: `b${i + 1}`}) ); } function handle(evt) { if (evt.target.classList.contains(`close-image`)) { console.clear(); console.log(`you clicked a button with id #${evt.target.id}`); } }
 button { margin-right: 0.2rem; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM