事件在jquery中单击按钮时调用两次

时间:2015-02-27 13:22:00

标签: jquery

我点击了一个提交按钮,我首先在javascript中调用click函数。

var id = $('input[id$=chkSubcontracting]').attr("id");
var indexserverIdPrefix = id.indexOf("chkSubcontracting");
var serverId= id.substring(0,indexserverIdPrefix);
$('#'+ serverId +'historyControl_historySubmitButton').click(function() {

//other part of code
//if error is there then add the error message to message

 if (message != "") {    
        $('#'+ serverId +'ErrorMessagePanelHiddenField').val("1");
        $(this.ErrorMessagePanelHiddenField).val("1");
        $("[id*='ErrorMessagePanelHiddenField']").val("1");
        this.IsValid = 1;
          alert(message);
         } 
else
 { 
         $("[id*='ErrorMessagePanelHiddenField']").val("0");
}

我的Aspx页面代码在这里

<asp:Panel ID="ErrorMessagePanel" CssClass="ErrorPanel" Visible="true" runat="server">
                    <asp:HiddenField ID="ErrorMessagePanelHiddenField" runat="server" />
                    <div class="ErrorDiv" id="ErrorMessageDiv">
                        <asp:BulletedList CssClass="ErrorMessage" ID="ErrorMessageBulletedList" runat="server">
                        </asp:BulletedList>
                    </div>
                </asp:Panel>

有时在按钮上单击此事件会被触发两次。我也可以设置&#39; ErrorMessagePanelHiddenField&#39;价值第一次。但不是在以后的时间。

1 个答案:

答案 0 :(得分:2)

如果多次在元素上调用jQuery .click(),则会多次附加事件处理程序。确保您在附加了单击事件处理程序的位置发布的脚本未在页面中执行多次。见click() event is calling twice in jquery

另一种方法是使用jQuery的.off().on()方法,如Using Jquery off().on() or just on()中所述。从本质上讲,.off()方法将删除所有附加的事件处理程序,因此您可以确保在调用.on()附加单击处理程序时,它将是唯一附加的处理程序。