简体   繁体   English

创建一个在事件侦听器被触发时返回的函数

[英]Create a function which returns on event listener being triggered

In JavaScript, I have an event listener and I have a separate function that needs to return a value only when the listener is triggered.在 JavaScript 中,我有一个事件侦听器,并且有一个单独的函数,该函数仅在触发侦听器时才需要返回一个值。

Example of what I am looking for:我正在寻找的示例:

document.getElementById("myBtn").addEventListener("click", function(){ alert("Hello World!"); });



function test(){ 
//check if myBtn has been pressed then return 1;
//otherwise keep waiting and don't return anything until myBtn is clicked.
}

How can I do something like this?我怎么能做这样的事情?

var is_button_pressed = 0;

document.getElementById("myBtn").addEventListener("click", function(){ 
    is_button_pressed = 1;
});



 function test(){ 
    return is_button_pressed===1?1:undefined;
}

You could just use test() inside your original event listener and then for the event listener inside test(), use a closure to check the value of myBtn, and then return the value you want.您可以在原始事件侦听器中使用 test() ,然后在 test() 中使用事件侦听器,使用闭包检查 myBtn 的值,然后返回所需的值。

Honestly, I don't understand the point of 2 event listeners inside each other.老实说,我不明白彼此内部的 2 个事件侦听器的意义。 For a RESTful request, why would you want to pause the request.对于 RESTful 请求,为什么要暂停请求。 You could just as simply capture the parameters of the request with the 1st button, and use the 2nd button to actually send the request.您可以简单地使用第一个按钮捕获请求的参数,然后使用第二个按钮实际发送请求。 This is a lot easier to code and reason about.这更容易编码和推理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 菜单粘贴触发了哪个事件? - Which event is being triggered from a menu paste? 焦点事件侦听器上的元素未使用element.focus()触发 - Element on focus event listener is not being triggered using element.focus() 点击事件监听器被重复触发而没有任何点击? - Click event listener is being repeatedly triggered without any clicks? 如何确定哪个元素触发了事件侦听器? - How to determine which element has triggered event listener? JavaScript中的事件点击未触发功能 - Function is not being triggered on event click in JavaScript 功能未执行。 滚动事件监听器 - Function not being executed. Scroll Event Listener 如何防止事件监听器 function 被同时触发多次 - how to prevent a event listener function to be triggered several times at the same time JS:如何在不附加事件侦听器的情况下触发该函数? - JS: How would this function get triggered without attaching an event listener on it? 当我在D3中触发的事件中删除相应的元素时,如何删除元素的事件侦听器? - How to remove event listener of an element when I remove the corresponding element in the midst of the event being triggered in D3? jQuery:事件监听器未触发 - jQuery: event listener not getting triggered
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM