按钮onclick功能触发两次 [英] button onclick function firing twice

查看:499
本文介绍了按钮onclick功能触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用事件处理程序调用javascript函数的按钮.由于某种原因,事件处理程序被调用了两次.

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

这是我的按钮(我正在使用php对象生成代码,这就是为什么有很多空标签的原因):

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.

我尝试在按钮的onclick属性中调用函数addToCart,但是如果我这样尝试,则会出现此错误:

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

我也尝试过event.preventDefault()和event.stopPropagation(),但都没有用.

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

有什么想法为什么会发生这种情况,或者我可以做些什么来阻止它执行两次,或者如果我从onclick ="调用javascript函数时为什么会出错呢?

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

推荐答案

也许您在同一按钮上两次附加了该事件.您可以做的是取消绑定任何先前设置的单击事件,如下所示:

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

这篇关于按钮onclick功能触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆