【问题标题】:JQuery - trigger change when change is made manuallyJQuery - 手动进行更改时触发更改
【发布时间】:2017-03-08 12:21:28
【问题描述】:

我有以下代码:

<div>
   <label>Location</label>
   <asp:TextBox ID="Location" runat="server" CssClass="form-control" ClientIDMode="Static" placeholder="Enter location"></asp:TextBox>
</div>
<div>
    <label >Address</label>
    <asp:TextBox ID="Address" runat="server" CssClass="form-control"    ClientIDMode="Static" placeholder="Enter the address"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="Address is Required" Display="Dynamic"  ControlToValidate="Address" CssClass="field-validation-error" EnableClientScript="True"></asp:RequiredFieldValidator>
</div>
<asp:Button ID="Submit" runat="server" Text="Save" OnClick="btnSubmit_Click" CssClass="btn btn-primary" />  

<script>
    $("#Location").on('change', function (e) {
        var location =  $("#Location").val();
        $("#Address").val(location).trigger("change");
    });

    $("#Address").on('change', function (e) {
        // do some other stuff
    });
</script>

Address 字段通过 jQuery 填充 Location 字段的值。

如果我在未填写任何字段的情况下单击提交,则会启动客户端验证,并且会在地址控件下方显示错误消息。

如果我现在在 Location 字段中输入一个值,jQuery 会触发并且 Address 字段会填充一个值,但之前的错误消息并没有清除。为了解决这个问题,我使用.trigger("change"); 方法。

但是每次我使用.trigger("change") 时,它调用它也会触发以下函数:

$("#Address").on('change', function (e) {
    // do some other stuff
});

我只想在手动更改输入而不是通过 jQuery 更改输入时触发更改事件处理程序上的地址。

我怎样才能做到这一点?

【问题讨论】:

  • 您的错误消息在哪里显示。出错时是否向输入添加属性。

标签: javascript jquery


【解决方案1】:

手动更改输入然后根本不绑定更改事件处理程序。

手动更改值时应绑定事件处理程序,并使用.off() 删除事件侦听器。

function AddressEventHandler(e) {
  // do some other stuff
}

$("#Location").on('change', function(e) {
  var location = $("#Location").val();

  $("#Address").val(location)
    .on('change.myNamespace', AddressEventHandler)
    .trigger("change.myNamespace")
    .off('change.myNamespace');
});

【讨论】:

    【解决方案2】:

    我已经设法通过执行以下操作来修复:

    $("#Address").on('change', function (e) {
    
        if (e.originalEvent !== undefined)
        {
           // do some other stuff
         }
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-29
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2017-12-10
      • 1970-01-01
      • 2021-01-27
      • 2011-09-19
      相关资源
      最近更新 更多