【问题标题】:How to click a button after e.preventDefault()?如何在 e.preventDefault() 之后单击按钮?
【发布时间】:2021-08-14 10:03:33
【问题描述】:

我试图阻止一个 click() 事件 在我使用 unbind() 将按钮取消绑定到事件处理程序后使用 preventDefault() 按钮,但它不起作用。

<script>
  $("#update2FAButton").on("click",function(e){
    e.preventDefault()
    var providedPassword = prompt("Enter passowrd");
    var password = $("#password").val();
    if (providedPassword!==password){
      alert("Wrong password, try again.");
    }
    if (providedPassword===password){ 
      $(this).unbind(e);
      $(this).click();
    }
    

  })
</script>

【问题讨论】:

  • $(this).unbind(e); -> $(this).off("click");可能 你想要 $(this).click(); -> this.click(); (或明确 $(this)[0].click(); - 即 DOM 元素点击)。
  • 太棒了!谢谢@freedomn-m。它有效:)

标签: javascript jquery button click


【解决方案1】:

虽然$(this).unbind 可能会起作用,但它自 1.7 以来一直是 discouraged,自 3.0 以来已弃用,由 $(this).off 取代。

unbind/off 的语法是

$(this).off("eventname")

所以你的情况是:$(this).off("click") 删除你的事件处理程序。

另外,如果您删除了 jquery 事件处理程序,那么 $(this).click() 将什么也不做,因此您需要触发单击 DOM 元素(而不是 jquery 的事件):

this.click();

额外

请注意,.off("click") 将禁用 所有 jquery 事件处理程序 - 在这种情况下,这可能是您想要的,在某些情况下,您可能不想删除其他事件处理程序。

您可以“命名空间”事件并仅关闭您想要的事件,例如:

$("#clickme").on("click.runonce", function() {
    console.log("runonce");
    // yes, this could be `.one` but here to serve as an example
    $("#clickme").off("click.runonce");
});

$("#clickme").on("click.always", function() {
    // not disabled by `.off("click.runonce")`
    console.log("runalways");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="clickme" type="button">click me</button>

【讨论】:

  • 哦!谢谢你的解释先生,现在我知道为什么我的代码不起作用了。顺便说一句,我正在使用 jquery-3.5.1。
猜你喜欢
  • 1970-01-01
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多