button onclick function firing twice

后端 未结 7 1571
天涯浪人
天涯浪人 2020-12-08 00:20

I have a button that calls a javascript function using an event handler. For some reason, the event handler is being called twice.

Here is my button (I am using a ph

相关标签:
7条回答
  • 2020-12-08 00:56

    You probably want to pass in the event and add

    $('.addToCartButton').click(function(e) {
      e.preventDefault(); //Added this
      alert("bob");
      //addToCart($(this).attr("id"));
    });
    

    OR

    $('.addToCartButton').click(function(e) {
      e.preventDefault(); //Added this
      alert("bob");
      //addToCart($(this).attr("id"));
      return false;
    });
    
    0 讨论(0)
  • 2020-12-08 01:01

    For me, I found out my events were not bound to my mapped component. The relevant answer is at Why is my onClick being called on render? - React.js but to provide some insights I've copied some of the answer below (Hope this helps!):

    1. using .bind

    activatePlaylist.bind(this, playlist.playlist_id)
    

    2. using arrow function

    onClick={ () => this.activatePlaylist(playlist.playlist_id) }
    

    3. or return function from activatePlaylist

    activatePlaylist(playlistId) {
      return function () {
         // you code 
      }
    }
    
    0 讨论(0)
  • 2020-12-08 01:04

    I know this is an old post, but for this type of error:

    • It may be that you have duplicate events bound
    • Either the event handler could be hooked up twice, or maybe the event isn't being unbound, after the intended listener(s) have finished listening and have done their job.

    In this case, you need to do something to unbind the listener once you no longer need to listen.

    0 讨论(0)
  • 2020-12-08 01:05

    My event was firing twice because I accidentally included both my_scripts.js AND my_scripts.min.js. Ensure you only include one.

    0 讨论(0)
  • 2020-12-08 01:09

    Maybe you are attaching the event twice on the same button. What you could do is unbind any previously set click events like this:

    $('.addToCartButton').unbind('click').click(function() {
        alert("bob");
        //addToCart($(this).attr("id"));
    });
    

    This works for all attached events (mouseover, mouseout, click, ...)

    0 讨论(0)
  • 2020-12-08 01:10

    Unbind event from selector and after appending in element in DOM again trigger event on specific selector.. $("selector_name").unbind( "event" ); //After this call event on selector again..

    For example:

    $( "#button" ).unbind( "click" );
    
    $("#button").click(function(event) {
    console.log("button click again);
    });
    
    0 讨论(0)
提交回复
热议问题