Javascript窗口确认弹出几次

javascript window confirm pops up several times

本文关键字:几次 窗口 确认 Javascript      更新时间:2023-09-26

我试图使用确认方法,但由于某种原因,确认窗口弹出几次。我谷歌和尝试不同的东西,但不幸的是,我不能得到它正常运行。代码如下:

//user clicks on the delete button
$("#deletePopUpImage").click(function(){
        console.log("deletePopUpimageCalled");
        //get the id of the image
        id = ($(this).parent().prop("id"));
        //create the ajax request
        data = "typ=function&functionType=deleteUserImage&id="+id;
        //open the confirm box
        var r = confirm("Are you sure that you want to delete this image?");
        if (r == true) {
            console.log("loadAjaxCAlled");
            //Ajax call
            loadAjax(data);
            //hide the image and the loader
            hideImagePopup();
        } else {
            //do nothing
        }  
    });

奇怪的是,确认窗口有时会弹出两次,有时会弹出三次,有时会弹出一次。这就是插入两个console.logs的原因。

" deletepopupimageccalled "总是只出现一次。然而,"loadAjaxCAlled"出现了几次。

在Ajax请求的成功回调中,我只是隐藏了缩略图div。

你知道我上面的代码有什么问题吗?

谢谢Stefan

可能是附加事件的代码:

$("#deletePopUpImage").click(function(){...});

被调用多次。每次调用.click(…)都会生成一个新的处理程序,该处理程序在按钮被单击时触发。

一些浏览器将相同的条目堆叠到一个日志中(因此日志不会扩展得那么快),这可能是你没有多次看到"deletepopupimageccalled"的原因。最好通过在浏览器中调试来检查。

我找到问题了。在Ajax成功处理程序中,我将已删除的图像的div设置为display:none,而不是删除它。因此,除法可以发生两次,三次等。在将代码更改为delete后,它运行得很顺利。