[英]How to display a random html file on an onclick event using javascript?
我正在尝试从四个不同的 html 文件中显示一个随机 html 文件,但我不太确定该怎么做。 到目前为止,我已经尝试了以下代码,但是得到了一个 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;
}
我意识到我在这里可能做错了很多,但我是编程新手,并且正在寻找一种方法来做到这一点。 因此,如果有人对如何解决这个问题有任何建议,或者有其他方法,我将不胜感激,因为我已经在网上搜索了似乎永恒的东西,但还没有找到解决方案。
谢谢,亚什。
你有多余的加号:
window.location.href = + randomizeVariations;
您的代码几乎是完美的。
问题是,在您设置新 URL 的行中,有一个+
。
一元+
运算符将其操作数转换为数字,因此在这种情况下,将randomizeVariations
转换为NaN
。
当您将其分配给location.href
时(显然),您将无法获得所需的效果。
要解决它,请删除+
运算符:
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.