1

我对 Javascript 还很陌生,正在尝试构建一个简单的照片查看器、幻灯片应用程序。我可能在代码中存在我还不知道的错误/错误做法。幻灯片按钮上的事件触发,我可以在控制台中看到输出,但是随机幻灯片按钮上的事件不会触发。

HTML5 片段

<form>
   <div id="controls">
       <input type="button" id="slideshow" value="Slide Show" />
       <input type="button" id="randomSlideshow" value="Random Slide Show" />
   </div>
</form>
<script src="js/PhotoViewer.js"></script>
</body>

JS 片段

var photosArrayGlobal = new Array();
var photoIndexGlobal = 0;
var displayGlobal;

window.onload = main;

function main() {
  "use strict";
  document.getElementById("slideshow").onclick = getArrayPhotosNames;

  document.getElementById("randomSlideshow").onclick = randomize(photosArrayGlobal);

  displayGlobal = document.getElementById("myImage");

  document.getElementById("nextSlide").onclick = function () {
    displayGlobal.setAttribute("src", photosArrayGlobal[1]); //Test value, image 2
  };
}

function getArrayPhotosNames() {
  var folderName = document.getElementById("photoFolder").value;
  var commonName = document.getElementById("commonName").value;
  var startNum = document.getElementById("startNum").value;
  var endNum = document.getElementById("endNum").value;
  var j = 0;

  if (startNum > endNum) {
    alert("Invalid Numbers");
  }

  var nameArray = new Array();

  for (var i = startNum; i <= endNum; i++) {
    nameArray[j] = folderName + commonName + i + ".jpg";
    j++;
  }

  photosArrayGlobal = nameArray.slice();
   console.log(photosArrayGlobal);

  return nameArray;
}

function randomize(dataArray) {
  var i = dataArray.length;
  var j, tempi, tempj;
  if (i === 0) {
    return false;
  }

  while (--i) {
    j = Math.floor(Math.random() * (i + 1));
    tempi = dataArray[i];
    tempj = dataArray[j];
    dataArray[i] = tempj;
    dataArray[j] = tempi;
  }
 console.log(dataArray);

}
4

1 回答 1

1

onclick处理程序需要一个函数,但您将函数返回的值传递给它(randomize()恰好是undefined)。将其更改为以下内容:

document.getElementById("randomSlideshow").onclick = function() {
    randomize(photosArrayGlobal);
};
于 2013-01-09T22:18:53.247 回答