首页 > 解决方案 > 在单击事件完成之前防止执行其余功能

问题描述

一直在为这个游戏苦苦挣扎。我有一个外部函数,它将两个变量声明为函数,然后将它们放入创建模态的函数中。用户将能够单击模态中的两个内部功能之一,但不能同时单击两者。一旦他们点击,就会创建一个新的事件监听器(通过他们选择的内部函数),然后他们点击网页上的其他地方来执行他们的操作。

内部函数做不同的事情,但为了这个例子,我把它们做成了一样的。

我想要实现的是outer在内部函数的事件侦听器之一完成之前不触发的最后一部分。

function inner1(a,b){

$(a).on("click", function() {

console.log("b");

}

function inner2(c,d){

$(c).on("click", function() {

console.log("d");

}



function outer(){

let x = function() {inner1(a,b)};
let y = function() {inner2(c,d)};

createModal{x,y} //creates a modal with some CSS, binding x and y to two buttons

afterEvent(); // want to trigger this AFTER createModal has created the modal AND after the user has clicked on the modal AND has clicked on the event listener.
}

outer() //--> outer executes when the user clicks on "start"

对于上下文,模态可能提供“增加金钱”或“增加点数”的选择。如果他们选择“增加金钱”,则会在网页的“金钱”区域创建一个新的事件列表,当他们点击它时,金钱就会出现。为了这个例子,我简化了函数,但这就是内部函数创建另一个事件监听器的原因——用户必须输入才能运行。

此外,andafterEvent()将是混合匹配的(因此使用 createModal 函数来构建它),所以我不能只把and放在里面。inner1()inner2()afterEvent()inner1()inner2()

我已经搞砸了 promises、return、皱眉头的全局变量、for 循环和 while 循环,但还不能产生我需要的东西。希望有人可以提供一些启示。

用户将如何看待这一点:

“好的,我点击开始,然后弹出一个模式,如果我点击牛,我会增加我的钱,如果我点击猪,我会增加我的积分。无论我选择哪个,在我完成之后行动,会随机抽一张新卡给我。好吧……就这样吧。我会点击模态的第一个选项。嘿,知道牛有轮廓,可以点击!我点击了它,增加了我的钱,现在为我抽了一张牌。”

标签: javascriptfunctionpromiseevent-listener

解决方案


像这样的东西?

function inner1(a,b, fn){

$(a).on("click", function() {

console.log("b");
fn();

}

function inner2(c,d, fn){

$(c).on("click", function() {

console.log("d");
fn();

}



function outer(){

let fn = () => afterEvent(); // want to trigger this AFTER createModal has created the modal AND after the user has clicked on the modal AND has clicked on the event listener.
let x = function() {inner1(a,b, fn)};
let y = function() {inner2(c,d, fn)};

createModal{x,y} //creates a modal with some CSS, binding x and y to two buttons

}

outer() //--> outer executes when the user clicks on "start"

推荐阅读