[英]Using 'onclick' in html for a javascript function only working once
[英]HTML onclick only working once with JavaScript
如上所述。 这是我尝试使用的那种代码的示例:
http://codepen.io/anon/pen/LGLJXd
<button id='myButt' onclick='randGen()'>New Target</button>
<button id="myOtherButt" onclick='clear()'>Clear</button>
<p id='test'>Click me to randomly choose from the array!</p>
然后是JS;
var myArray = ["Empire", "Rebels", "Scum", "Clones", "Trade Federation", "Sith", "Jedi"];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
function randGen() {
document.getElementById('test').innerHTML = rand;
};
function clear() {
document.getElementById('test').innerHTML = 'No';
};
它一次运行良好,但是“清除”或尝试多次使用“第一”按钮没有响应。 有人可以帮助我了解我做错了什么吗?
页面加载时,您已经生成了一次随机变量,并且它永远不会改变。 为了更改它,您需要在单击时再次生成它:
var myArray = ["Empire", "Rebels", "Scum", "Clones", "Trade Federation", "Sith", "Jedi"];
function randGen() {
var rand = myArray[Math.floor(Math.random() * myArray.length)];
document.getElementById('test').innerHTML = rand;
};
您正在调用rand
,它只是一次生成的变量。
如果要获取另一个随机项,则应使用返回结果的函数:
function rand() {
var myArray = ["Empire", "Rebels", "Scum", "Clones", "Trade Federation", "Sith", "Jedi"];
return myArray[Math.floor(Math.random() * myArray.length)];
}
function randGen() {
document.getElementById('test').innerHTML = rand();
};
function clear() {
document.getElementById('test').innerHTML = 'No';
};
这里的问题是仅在开始时才初始化属性“ rand”。 因此,每次调用函数“ randGen()”时,“ rand”属性都使用相同的值。
为了始终获得新值,您还必须将rand设置为新值。
解决方法很简单:
function randGen() {
// get a new value
var rand = myArray[Math.floor(Math.random() * myArray.length)];
// set the value
document.getElementById('test').innerHTML = rand;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.