onclick触发两次_按钮onclick功能触发两次

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):

Add To Cart

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 οnclick=""?

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值