[英]How to display a random html file on an onclick event using javascript?
I am trying to display a random html file out of four different html files, and am not quite sure how to do that.我正在尝试从四个不同的 html 文件中显示一个随机 html 文件,但我不太确定该怎么做。 So far, I have tried the following code, but get an NaN error- the web browser cannot find the file:
到目前为止,我已经尝试了以下代码,但是得到了一个 NaN 错误——web 浏览器找不到该文件:
<script type="text/javascript">
var allVariations = ["/exp1.html","/exp2.html","/exp3.html","/exp4.html"];
var randomizeVariations = allVariations[Math.floor(Math.random()*allVariations.length)];
document.getElementById('loading').onclick = function() {
if (document.getElementById('consent_checkbox').checked) {
window.location.href = + randomizeVariations;
} else {
alert('You need to check the checkbox to continue.');
return false;
}
return false;
}
I realize I might be doing plenty wrong here, but I am new to programming, and am looking for a way to do this.我意识到我在这里可能做错了很多,但我是编程新手,并且正在寻找一种方法来做到这一点。 So if anyone has any suggestions as to how to fix this, or have another way of doing it, I would appreciate it, because I have searched online for what seems like an eternity, and haven't yet found a solution yet.
因此,如果有人对如何解决这个问题有任何建议,或者有其他方法,我将不胜感激,因为我已经在网上搜索了似乎永恒的东西,但还没有找到解决方案。
Thanks, Yash.谢谢,亚什。
You got redundant plus sign:你有多余的加号:
window.location.href = + randomizeVariations;
Your code is almost perfect.您的代码几乎是完美的。
The issue is, that in the line where you set the new URL, there is a +
.问题是,在您设置新 URL 的行中,有一个
+
。
A unary +
operator converts its operand into a number, so in this case, converts randomizeVariations
into NaN
.一元
+
运算符将其操作数转换为数字,因此在这种情况下,将randomizeVariations
转换为NaN
。
When you assign it to location.href
(obviously) you won't get the desired effect.当您将其分配给
location.href
时(显然),您将无法获得所需的效果。
To solve it, remove the +
operator:要解决它,请删除
+
运算符:
var allVariations = ["/exp1.html", "/exp2.html", "/exp3.html", "/exp4.html"];
var randomizeVariations = allVariations[Math.floor(Math.random() * allVariations.length)];
document.getElementById('loading').onclick = function() {
if (document.getElementById('consent_checkbox').checked) {
window.location.href = randomizeVariations;
} else {
alert('You need to check the checkbox to continue.');
return false;
}
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.