这是一个简单的骰子投掷事件,6个骰子,由随机数生成,一切正常,我在控制台中获取数据,但我希望它只在单击按钮时触发.
在这段代码中触发onclick事件(在控制台中),没有我点击,我该如何解决?
<!doctype html>
<html lang="eng">
<head>
<meta charset="utf-8" />
<title>Yahtzee Project OOP</title>
<link href= rel='stylesheet' type='text/css'>
</head>
<body>
<h1>Dice Project</h1>
<button id="rollButton">ROLL CLICK HERE</button>
<script >
var results = [
{ rollCounter: 0},
{ dieNumber: 1, rollResult: 'NULL', check: 'NULL'},
{ dieNumber: 2, rollResult: 'NULL', check: 'NULL'},
{ dieNumber: 3, rollResult: 'NULL', check: 'NULL'},
{ dieNumber: 4, rollResult: 'NULL', check: 'NULL'},
{ dieNumber: 5, rollResult: 'NULL', check: 'NULL'}
];
var clickButton = document.getElementById('rollButton');
function print(message){
document.write(message);
}
function randomRoll(){
return Math.floor(Math.random() * (6 - 1 + 1)) + 1;
}
function rollDice(results){
for (var i=1; i<6; i++){
results[i].rollResult = randomRoll();
}
console.log(results);
return results;
}
clickButton.onclick = rollDice(results);
</script>
</body></html>Run Code Online (Sandbox Code Playgroud)
那是因为你要将执行结果分配rollDice(results)给你的clickButton.onclick函数.单击该元素时,您没有告诉它执行该函数.要避免这种情况,请将其包装在函数调用本身中:
clickButton.onclick = function() { rollDice(results); }
Run Code Online (Sandbox Code Playgroud)
现在,您的点击将执行该功能,然后才执行该rollDice功能.
扩展这里发生的事情.假设我们有一个foo返回字符串的函数"bar":
function foo() { return "bar"; }
Run Code Online (Sandbox Code Playgroud)
如果我们要分配foo()给一个新变量,JavaScript将在foo那里执行该函数,然后将该函数的结果分配给我们的新变量:
var baz = foo();
-> "bar"
Run Code Online (Sandbox Code Playgroud)
但是,如果我们将foo()函数调用放在另一个函数调用中,我们的原始函数将不会立即执行:
var baz = function() { return foo(); }
-> function() { return foo(); }
Run Code Online (Sandbox Code Playgroud)
如果我们现在调用baz(),它将执行自己的函数,该函数本身执行我们的原始foo函数:
baz();
-> "bar"
Run Code Online (Sandbox Code Playgroud)
这同样适用于您的onclick功能.而不是在onclick单击元素时告诉执行我们的函数,我们将分配"bar"给我们的onclick函数:
elem.onclick = foo();
-> "bar"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1254 次 |
| 最近记录: |