【问题标题】:Clicking cancel on confirmation box does not cancel the action单击确认框上的取消不会取消操作
【发布时间】:2015-01-29 03:01:35
【问题描述】:
var Main = {
    addConfirmations: function() {
        var e = document.querySelectorAll(".bg-red");
        for (var t = 0; t < e.length; t++) {
            e[t].addEventListener("click", function() {
                var e = this.getAttribute("title");
                Main.confirmation(e)
            })
        }
    },
    confirmation: function(e) {
        if (e === null || e.toString().length === 0) {
            e = "Are you sure you want to proceed?"
        }
        return window.confirm(e);
    }
}
window.onload = Main.addConfirmations

HTML:

<input type="submit" class="bg-red" value="Delete">

嗨,我在我的网站中使用了上述功能,以便它为每个具有红色背景的按钮添加一个确认框。现在这似乎正在工作,每当我点击时都会弹出一个确认框但是,一个红色按钮,如果我单击确认框上的取消,它不会取消操作。这让我烦恼了好几个小时。我尝试了很多调试,但似乎找不到它。有人可以帮忙吗?

【问题讨论】:

  • 您要阻止的操作是什么?
  • e.preventDefault() 将停止操作。
  • 好吧,你不要取消操作....
  • 首先,请尽量在编码中使用相关的变量名。其次,处理确认响应并采取相应措施。 var isOk=Main.confirmation(e);if(isOk===false) event.preventDefault();
  • 我不使用 jQuery。有没有JS解决方案?

标签: javascript object confirm


【解决方案1】:

好吧,你从确认方法返回,但你在调用它的地方什么也不做。

var Main = {
    addConfirmations: function() {
        var e = document.querySelectorAll(".bg-red");
        for (var t = 0; t < e.length; t++) {
            e[t].addEventListener("click", function (event) {
                var title = this.getAttribute("title");
                var check = Main.confirmation(title);
                if(!check) {
                    event.preventDefault ? event.preventDefault() : event.returnValue = false;          
                }
            }, true);
        }
    },
    confirmation: function (message) {
        if (!message || !message.length) {
            message = "Are you sure you want to proceed?"
        }
        return window.confirm(message);
    }
}
window.onload = Main.addConfirmations
&lt;a href="http://www.example.com" class="bg-red"&gt;asdf&lt;/a&gt;

【讨论】:

  • 改为使用 preventDefault
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
相关资源
最近更新 更多