Jquery - 等待用户输入

2022-01-20 00:00:00 user-interface popup jquery javascript

我试图制作一个弹出窗口来确认用户的操作(例如,删除表格中的一行..).旨在使弹出窗口完全是 HTML 和 Javascript.我无法理解的是如何让 javascript 等待用户输入,但仍可用于其他 javascript 事件.(其他点击触发的东西,等等..).我想我会做的是像

im trying to make a popup that comes up to confirm a users action (deleting a row in a table, for example..). aiming at making the popup entirely HTML and Javascript. What i can't get my head around is how i would make the javascript wait for the users input, but still function for other javascript events. (other click triggered stuff, etc..). What i thought i'd do is something like

if(makePopup("Are you sure?") == true) {
 //bla bla 
}

makePopup 函数将创建一个包含传递给它的字符串的弹出窗口,并为用户提供是或否选项.在该函数的某个地方,我需要一个循环来等待用户单击是或否.代码只是在该行等待,直到完成某些事情.这就是我想要的......但是我的问题是......如果代码在那里陷入循环,jquery如何执行其他任务?例如,如果弹出框是可拖动的怎么办?当代码此时忙于循环时,这些效果的事件将如何触发..?只是现在无法解决解决方案..

where makePopup function would create a popup containing the string passed to it, and give the user a yes or no option. somewhere in that function i'd need a loop that would wait for the user to click yes or no. the code just waits at that line until something is done. which is what i want... but theres my problem.. if the code is stuck in a loop there, how can jquery perform other tasks? for example, what if the popup box was draggable? how will the events for these effects get trigged when the code is busy looping at that point..? just cant get my head around a solution right now..

这是我目前要测试的东西..

here's something i have at the moment to test..

        $(document).ready(function(){
        $('a').click(function(){
            makePopup("Wana go to google?",function(){
                window.location.replace("http://www.google.com");
            });
        });
    });

    function makePopup(msg,callback){
        $('body').append("<div class='popup'><p>"+msg+"</p></div>");
    }

仍然不确定如何进行确认.弹出窗口应包含一个是和否按钮.

still unsure of how to do the confirmation stuff. the popup should include a yes and no button.

推荐答案

你可以实现这样的东西

makePopup("Are you sure?", function {
  //bla bla 
});

只有当用户确定,在他点击一个按钮或其他什么之后,它才会调用你的回调.喜欢:

which will call your callback only if user sure, after he clicks a button or whatever. Smth like:

function makePopup(msg, callback) {
     $("#sureformmsg").html(msg);
     $("#sureform").show().submit(function() { if (..check..) callback(); });
}

<小时>

你的例子:


Your example:

$(document).ready(function(){
    $('a').click(function(){
        makePopup("Wana go to google?",function(){
            window.location.replace("http://www.google.com");
        });
    });
});

function makePopup(msg,callback){
    $('body').append("<div class='popup'><p id='themsg'>"+msg+"</p></div>");
    $('#themsg').onclick(callback);
}

相关文章