问题
I use a javascript to catch the x
and y
position 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?
<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>
回答1:
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);
}
回答2:
You can't.
JavaScript isn't capable of time travel.
The event handler function won't run until the event happens. By that time, the function that called addEventHandler
will have finished running and returned.
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.
来源:https://stackoverflow.com/questions/33501696/how-to-return-value-from-addeventlistener