我有一个网站,我想让它在每次加载页面时随机加载不同的HTML5 Javascript动画,JavaScript是迄今为止我最弱的技能之一,我提前感谢任何帮助,如果这恰好是重复(我已经尝试过搜索)然后请投票支持要关闭的问题。
基本上我使用的方法是脏的,很可能是它不起作用的原因,基本上我尝试了randommath并且没有运气并且把这归结为我的JS技能非常弱,替代方法看起来更容易吗?也可以工作,这基本上是在页面加载时插入HTML,例如a.html和b.html都包含不同的脚本。
这就是我的代码:
HTML
<html>
<head>
<script src="js/insert.js"></script><!-- This inserts the Random Page -->
</head>
<body onload="loadExternalHTMLPage()">
<div id="injectjs"> </div>
<canvas="id"> </canvas>
<script src="js/animation-lib-pageA.js"></script><!--Library for pageA -->
<script src="js/animation-lib-pageB.js"></script><!--Library for pageB -->
</body>
</html>
Inject.js
function loadExternalHTMLPage() {
var xmlhttp;
var pagesToDisplay = ['a.html', 'b.html'];
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("jsinsert").innerHTML = xmlhttp.responseText;
}
}
var randomnumber = Math.floor(Math.random() * pagesToDisplay.length);
xmlhttp.open("GET", pagesToDisplay[randomnumber], true);
xmlhttp.send();
}
大多数JS Guru应该能够看到我在页面加载时随机插入a.html和b.html,现在这样可行,但问题是a.html和b.html中包含的脚本没有执行。 (使用firebug我可以清楚地看到脚本按预期插入)。
所以例如a和b看起来像:
a.html
<script> window.onload = function () { }</script>
b.html
<script> window.onload = function () { } </script>
基本上A和B中的代码是有效的,并且在此插入中正常工作,我将上面的示例填充为占位符。 A和B都包含执行画布中包含的动画的JavaScript,但它目前无法正常工作,我怀疑它与我在加载页面后加载脚本的事实有关。提前谢谢。
答案 0 :(得分:1)
您始终可以使用eval()
执行您下载的内容... :)(不推荐)。
或者您可以修改服务器上的html页面,以便在将页面提供给用户之前包含您想要的随机脚本(您没有声明平台),因为它在页面加载时无论如何都会更改。
答案 1 :(得分:1)
您可以为A或B随机加载html,然后运行其动画。
此示例使用jQuery,这使得加载远程html的任务更容易。这是jquery .load函数的链接,它用已下载的html替换现有元素html:http://api.jquery.com/load/如果你想要纯javascript,你可以使用[messier!]替代方案,但逻辑保持不变。 / p>
以下是步骤:
这是入门代码。 (确保包含jQuery库)
<script>
window.onload(){
// randomly load html+animation A or B
if(Math.random()<.50){
$('#injectjs').load(
'yourSite.com/HtmlForA.html', // first load the html for A
function(){ animationA(); } // then run animationA
);
}else{
$('#injectjs').load(
'yourSite.com/HtmlForB.html', // first load the html for B
function(){ animationB(); } // then run animationB
);
}
}
</script>