简体   繁体   中英

JQUERY Click event doesn't work only at the first click call

In the code, I try to print the name that is saved as a data value for each button.. but on the first click event call it doesn't work. while after the first time it works normally.

NOTE: off('click') function it is because without it this function fires multiple times with the following rate: 1times on a click, 2times on the next click, 3times on the next click, 4times on the next click, ...... and so on.

So it(off('click')) prevents this to happen.

$(document).on('click', '.btn-add', () => {

   $(".btn-add").off('click').on('click', (obj) => {

      const nameOfProduct = obj.currentTarget.value;

      console.log("name selected = " + nameOfProduct);

   })

})

This is probably what you want to do, after document is ready, add button click handler:

 $(document).ready(() => {
    $(".btn-add").on('click', (obj) => {

      const nameOfProduct = obj.currentTarget.value;

      console.log("name selected = " + nameOfProduct);

   })
 })

Your code removes handler then adds handler to the button click after every click on button.. So after first click, you try to remove, then you add handler. After that you fire handler function, remove handler and add handler, which is probably not what you want to do.

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