javascript - 脚本无法放置在正文标记中

标签 javascript html

名为 One.jpg 到 Ten.jpg 的图像位于我桌面上的文件夹“myFolder”中。下面是一次从 myFolder 中总共十个图像中旋转三个图像的代码,并且 html 文件也在同一文件夹中。如何编写 src 以便此代码可以工作。警报消息给出了这 10 个图像的名称,但进一步它不起作用。脚本无法放置在正文标签中。有什么问题需要纠正以加快结果。

<html>
<body>

<img  id = "im1"><img id = "im2"><img id = "im3">

<script type = "text/javascript">

var imgArray = ['One.jpg','Two.jpg','Three.jpg','Four.jpg','Five.jpg', 'Six.jpg', 'Seven.jpg', 'Eight.jpg', 'Nine.jpg', 'Ten.jpg'];

function randOrd(){return (Math.round(Math.random())-0.5)}
imgArray.sort(randOrd);
alert (imgArray);  // FOR TESTING
var len = imgArray.length;
var count = 0;

rotate1();
rotate2();
rotate3();

function rotate1() {
document.getElementById("im1").src= imgArray[count];
count++;
if (count>=len) {count = 0}
var tim1 = window.setTimeout("rotate1()", 3000);  // 3 seconds
}


function rotate2() {
document.getElementById("im2").src = imgArray[count];
count++;
if (count>=len) {count = 0}
var tim2 = window.setTimeout("rotate2()", 5000);  // 5 seconds
}


function rotate3() {
document.getElementById("im3").src = imgArray[count];
count++;
if (count>=len) {count = 0}
var tim3 = window.setTimeout("rotate3()", 7000);  // 7 seconds
}

</script>
</body>
</html>

最佳答案

最佳实践表明,脚本应放在单独的文件中,然后包含在正文的末尾,如下所示:

<script src="scripts/YourScript.js"></script>

其中 src 指向文件。

这很好,因为:

  • 浏览器从上到下解析页面时呈现页面。这意味着当它到达 body 标记末尾的 script 部分时,您的 HTML 应该被加载,因此您使用的元素脚本很可能会出现。

  • 您可以向用户显示一些内容,直到最慢的部分(脚本)加载。

  • 您可以从 CDN 提供脚本服务,这样请求-响应延迟就会最小。

据我所知,此规则的唯一异常(exception)是 modernizr 或类似的浏览器和功能检测库。

更新

这里缺少一个分号:

if (count>=len) {count = 0}

应该是这样的:

if (count>=len) {count = 0; }

此外,当您将函数传递给 setTimeout 时,您可以这样做:

window.setTimeout(rotate3, 7000);

关于javascript - 脚本无法放置在正文标记中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23453615/

相关文章:

javascript - Apollo React 为什么不能在 UseEffect 钩子(Hook)中查询

javascript - 使用 jQuery 在 html 数组中设置一个值

javascript - 如何在jquery中写一个函数

javascript - 如何在 iFrame 的设计模式中使用 MathJax?

html - 悬停时展开圆圈保持背景居中?

html - Logo 调整大小响应式 opencart

javascript - .NET Core 将 JavaScript 与 CSHTML 分离并访问 ViewData

javascript - 使用 cshtml 页面中 SQL 数据库表中的数据更新 html 表

javascript - 在 Javascript 中更新多个 id

html - 在 2 个不同的列中水平对齐 div