【问题标题】:Event Called twice on button click in jquery事件在 jquery 中单击按钮时调用了两次
【发布时间】:2015-02-27 13:21:59
【问题描述】:

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

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>

有时在按钮单击时此事件会触发两次。我也可以第一次设置“ErrorMessagePanelHiddenField”值。但不是在以后的时间。

【问题讨论】:

  • 请输入您的 html 标记
  • 每次点击提交按钮时是否总是两次,或者您的警报计数是否在增加?
  • @arkantos 并非总是如此。但是我无法第二次设置 hiddenfield。

标签: jquery


【解决方案1】:

如果您在一个元素上多次调用 jQuery .click(),事件处理程序将被附加多次。确保您发布的附加了 click 事件处理程序的脚本在您的页面中没有被多次执行。见click() event is calling twice in jquery

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    相关资源
    最近更新 更多