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

前端 未结 18 1544
借酒劲吻你
借酒劲吻你 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:39

    when you click div with addproduct class one event is fired for that particular element, not five. you're doing something wrong in you code if event is fired 5 times.

    0 讨论(0)
  • I solved it by using inline jquery function call like

    <input type="text" name="testfield" onClick="return testFunction(this)" /> 
    
    <script>
      function testFunction(current){
         // your code go here
      }
    </script>
    
    0 讨论(0)
  • 2020-11-29 00:41

    I think you add click event five times. Try to count how many times you do this.

    console.log('add click event')
    $(".addproduct").click(function(){ });
    
    0 讨论(0)
  • 2020-11-29 00:42
    $(document).on('click', '.addproduct', function () {
        // your function here
    });
    
    0 讨论(0)
  • 2020-11-29 00:43

    I had the same problem. The cause was that I had the same jquery several times. He was placed in a loop.

    $ (". AddProduct"). click (function () {});
    $ (". AddProduct"). click (function () {});
    $ (". AddProduct"). click (function () {});
    $ (". AddProduct"). click (function () {});
    $ (". AddProduct"). click (function () {});
    

    For this reason was firing multiple times

    0 讨论(0)
  • 2020-11-29 00:45

    This should fix it and should be a good habit: .unbind()

    $(".addproduct").unbind().click(function(){
       //do something 
    });
    
    0 讨论(0)
提交回复
热议问题