Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

javascript - button onclick function firing twice

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 php object to generate the code, that's why there are a lot of empty tags):

<button name="addToCart" value="" size="" onclick="" src="" class="addToCartButton" id="0011110421111" type="button" formtarget="_self" formmethod="post" formaction="" data-mini="true" width="" height="" placeholder="" data-mini="1" onkeypress="" >Add To Cart</button>

Here is my event handler:

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

Here, I am getting the alert twice.

I have tried calling the function addToCart in the button's onclick property, but if I try it that way, I get this error:

TypeError: '[object HTMLButtonElement]' is not a function (evaluating 'addToCart(0011110421111)')

I have also tried event.preventDefault() and event.stopPropagation(), and neither worked.

Any ideas why this is happening, or what I can do to stop it from executing twice, or maybe why I am getting an error if I call the javascript function from onclick=""?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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, ...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...