javascript 如何从 addEventListener 返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33501696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:32:57  来源:igfitidea点击:

How to return value from addEventListener

javascriptgetelementbyidaddeventlistener

提问by jdleung

I use a javascript to catch the xand yposition when user click a link, by now, I can make it works, but I want it to return the two values to function init()when it is called. How can I do it?

当用户单击链接时,我使用 javascript 来捕捉xy定位,现在,我可以让它工作,但我希望它在function init()调用时返回两个值。我该怎么做?

<script type="text/javascript">

  document.addEventListener("DOMContentLoaded", init, false);

  function init()
  {
    var canvas = document.getElementById("canvas");
    canvas.addEventListener("mousedown", getPosition, false);

    // how can I get the return values here?

  }

  function getPosition(event)
  {
    var x = new Number();
    var y = new Number();
    var canvas = document.getElementById("canvas");

    if (event.x != undefined && event.y != undefined)
    {
      x = event.x;
      y = event.y;
    }
    else
    {
      x = event.clientX + document.body.scrollLeft +
          document.documentElement.scrollLeft;
      y = event.clientY + document.body.scrollTop +
          document.documentElement.scrollTop;
    }

    x -= canvas.offsetLeft;
    y -= canvas.offsetTop;

    alert("x: " + x + "  y: " + y); // here can print the correct position

    // if I add the two values here, and return them. How can I receive the values in funciton init()
    // var clickPosition={"x":x, "y":y};
    // return clickPosition;
  }

</script>

回答by Jamiec

Where you have the comment, you will never be able to access the variables, the event has not occurred yet.

在您有评论的地方,您将永远无法访问变量,事件尚未发生。

Instead, what you can do is pass an anonymous function to the event handler, call your method which returns a value and use it as appropriate

相反,您可以做的是将匿名函数传递给事件处理程序,调用返回值的方法并根据需要使用它

function init()
{
    var canvas = document.getElementById("canvas");
    canvas.addEventListener("mousedown", function(event){
        var result = getPosition(event);

        // result is your return value
    }, false);

}

回答by Quentin

You can't.

你不能。

JavaScript isn't capable of time travel.

JavaScript 不能进行时间​​旅行。

The event handler function won't run until the event happens. By that time, the function that called addEventHandlerwill have finished running and returned.

事件处理函数在事件发生之前不会运行。到那时,调用的函数addEventHandler将完成运行并返回。

The event handler function needs to either deal with the data itself, or call other functions to do it. The data has to travel forwards, it can't go back.

事件处理函数要么自己处理数据,要么调用其他函数来完成。数据必须向前传播,不能返回。