如何从addEventListener返回值 [英] How to return value from addEventListener

查看:374
本文介绍了如何从addEventListener返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户单击链接时,我使用Javascript捕获 x y 位置.

I use Javascript to catch the x and y position for when user clicks a link.

我可以使其工作,但是我希望它在被调用时将两个值返回给 function init().

I can make it work, but I want it to return the two values to function init() when it is called.

我该怎么办?

<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>

推荐答案

在具有注释的位置,您将永远无法访问变量,但该事件尚未发生.

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);

}

这篇关于如何从addEventListener返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆