I minified my work in this simple code that represent my problem:
runSomething();
function runSomething(){
function getRandom(){
var random = Math.floor((Math.random())*10);
return random;
};
document.onclick = getRandom();
};
There is a external function ( runSomething()
) that contains the next:
getRandom
that returns a number between 0 - 9 (that i'm using to a select a random item of a array) document.onclick = getRandom();
that what is supposed to do, is RUN getRandom();
each time i click any place of the document, to get another new value But what happens? the document.onclick = getRandom();
just run once (when the document is being loaded) but nothing happens when a click the document
And getRandom()
must not be fired when the document is being loaded, because that function is fired in other part of the script, and thats mean that i will get 2 differents new values (remember that getRandom()
return different numbers each time that is fired)
What i'm doing wrong?
PS I still a rookie in JS
PPS Sorry for my english
Remove the ()
document.onclick = getRandom;
The ()
will invoke the function immediately on load, you have to pass the function along.
分配onClick时,需要分配函数而不是执行它并分配返回值(这是你的()
所做的):
document.onclick = getRandom;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.