简体   繁体   English

javascript在第二页上不起作用

[英]javascript not working on second page

I am implementing a image rotator on one of my pages, however I would like to re use the code on two other pages as well. 我正在其中一个页面上实现图像旋转器,但是我也想在其他两个页面上重新使用代码。 I would also like each page to rotate images in different a order to other pages. 我还希望每个页面以与其他页面不同的顺序旋转图像。 I thought this was covered by declaring different arrays and calling them with unique ids. 我认为这可以通过声明不同的数组并使用唯一的ID来覆盖。

The code is as follows 代码如下

 var ImageArr1 = new Array("/assets/function.jpg","assets/takeaway.jpg","/assets  /delivery.jpg");
 var ImageHolder1 = document.getElementById('Rotating1');


 var ImageArr2 = new Array("/assets/takeaway.jpg","/assets/function.jpg","/assets/delivery.jpg");
 var ImageHolder2 = document.getElementById('Rotating2');

  function RotateImages(whichHolder,Start)
  {
  var a = eval("ImageArr"+whichHolder);
   var b = eval("ImageHolder"+whichHolder);
  if(Start>=a.length)
  Start=0;
  b.src = a[Start];
  window.setTimeout("RotateImages("+whichHolder+","+(Start+1)+")",3000);
  }

  RotateImages(1,0);
  RotateImages(2,0);

And my HTML is as follows-Page1 我的HTML如下-Page1

<img src="/assets/function.jpg" name="Rotating" id="Rotating1" width="260" height="180" alt="">

Page 2 第2页

<img src="/assets/takeaway.jpg" name="Rotating" id="Rotating2" width="260" height="180" alt="">

I am slowly learning Javascript but this has got me stumped 我正在慢慢学习Javascript,但这让我很困惑

Any help appreciated 任何帮助表示赞赏

The problem you have is an error in fact. 您遇到的问题实际上是一个错误。 By calling b.src, you assert that b is defined but your ImageHolder might not be there. 通过调用b.src,您可以断言已经定义了b,但是ImageHolder可能不存在。 Especially by calling RotateImage(2... on page1 or RotateImage(1... on page2. 特别是通过调用第1页上的RotateImage(2 ...或第2页上的RotateImage(1 ...)。

First thing you might try is removing eval from your brain. 您可能要尝试的第一件事是消除大脑中的评估。 you can simply use window["ImageArr"+whichHolder], it's far better. 您只需使用window [“ ImageArr” + whichHolder],效果会更好。

Next, replace the end of your function (the two last lines) by 接下来,将函数的结尾(最后两行)替换为

if(b) {
    b.src = a[Start];
    window.setTimeout("RotateImages("+whichHolder+", "+(Start+1)+")", 3000);
}

Next, you may learn to call setTimeout with a function instead of a string : 接下来,您可以学习使用函数而不是字符串来调用setTimeout:

window.setTimeout(function() {
    RotateImages(whichHolder, Start+1);
}, 3000);

And finally, it's more code convention, classical variables and functions are not capitalized for the first letter. 最后,这是更多的代码约定,经典变量和函数的首字母不大写。 So it may be rotateImages and start. 因此它可能是rotationImages并开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM