jQuery $(“.class”).click(); - multiple elements, click event once

前端 未结 18 1670
借酒劲吻你
借酒劲吻你 2020-11-29 00:01

I have multiple classes on a page of the same name. I then have a .click() event in my JS. What I want to happen is the click event only happen once, regardless of multiple

18条回答
  •  隐瞒了意图╮
    2020-11-29 00:53

    This question have been resolved and also got a lot of responses, but i want to add something to it. I was trying to figure out, why my click element his firing 77 times, and not one time.

    in my code, i had an each, running a json response and displaying it as divs with buttons. And then i declared the click event inside the each.

    $(data).each(function(){
        button = $('

    If you write your your code like this, the class .test-button will get multiple click events. For example, my data has 77 lines, so the each will run 77 times, that means i will decline the click event on the class 77 times. When you click the element, it will be fired 77 times.

    But if you wirte it like this:

    $(data).each(function(){
        button = $('

    you are declaring the click element after the each. That means, the each will run its 77 times, and the click element will be declared only one time. So, if you click the element, it will be fired only one time.

提交回复
热议问题