問題描述
我有一個使用事件處理程序調用 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 函數觸發兩次的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!