【问题标题】:event.preventDefault() works for me on Chrome but not Firefox, why? [duplicate]event.preventDefault() 在 Chrome 上对我有效,但对 Firefox 无效,为什么? [复制]
【发布时间】:2023-03-09 15:25:02
【问题描述】:

在 Chrome 中,如果单击 window.confirm 中的取消按钮,则不会触发关闭日操作(由 go 后端提供支持)。但是,在 Firefox 中,即使单击取消也会触发该事件。两种浏览器都支持event.preventDefault,所以我不明白为什么它在 Chrome 中有效,但在 Firefox 中无效。

我的 Javascript:

document.getElementById("closeDay").addEventListener("click", createAlert);
    function createAlert(){
            x = window.confirm("Are you sure?");
            if(x === false){
                    event.preventDefault()
            }
    }
    

我的 HTML:

<form method="POST" action="/closeDay" id="closeDay">
    <input type="submit" value="Close Day" />
</form>

我尝试将 id 从表单移动到输入,但这没有区别。为了以防万一,我还将我的 js 脚本移到了文件的底部,但这也没有解决问题。

【问题讨论】:

  • event 在所有浏览器中都不是全局变量

标签: javascript html dom-events prompt


【解决方案1】:

您需要将event 作为函数参数传递

function createAlert(event){
  x = window.confirm("Are you sure?");
  if(x === false){
  event.preventDefault()
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    相关资源
    最近更新 更多