【问题标题】:Issue with image generator in html/javascripthtml/javascript 中的图像生成器问题
【发布时间】:2015-06-15 03:45:04
【问题描述】:

我环顾四周,试图为我的问题找到解决方案,但我不知道我的代码哪里出错了。我在我的网站上将代码拆分为两个文件,因此我将它们拆分为 html 和 javascript。

HTML:

<html>
<!-- 
-->
<script type="text/javascript" src="external_javascript.js"></script>

<form name="imageForm">
  <table border=3>
  <tr>
    <td>
      <input onclick="displayImage();" type=button value="Display Random Image">
    </td>
  </tr>
  <tr>
    <td>
      <img src="blank.jpg" name="canvas" />
    </td>
  </tr>
  </table>
</form>
</html>

Javascript:

<html>

<script> 
//create an array named imagesArray that contains the seven image file names
//dog.jpg, fox.jpg, mouse.jpg, alligator.jpg, fish.jpg, parrot.jpg and cat.jpg

var imagesArray = ["a.jpg", "b.jpg", "c.jpg", "d.jpg", "e.jpg", "f.jpg", "g.jpg"];


//create a function named displayImage
//it should not have any values passed into it

function displayImage(){

    //the first statement should generate a random number in the range 0 to 6 (the subscript values of the image file names in the imagesArray)
    var num = Math.floor(Math.random() * (imagesArray.length+1)); // 0...6
    //the second statement display the random image from the imagesArray array in the canvas image using the random number as the subscript value
    document.canvas.src = imagesArray[num];

}

//remember the subscript values of the array are 0 to 6 (seven elements) zero based array
//you will have to subtract 1 from the random number generated to account for the zero based array
</script>

</html>

我还上传了从 a.jpg 到 z.jpg 的图片到我的网站管理器,提前致谢!

【问题讨论】:

  • 外部 javascript 文件应该包含 HTML 标签

标签: javascript jquery html css stack


【解决方案1】:

您的.js-文件应如下所示:

var imagesArray = ["a.jpg", "b.jpg", "c.jpg", "d.jpg", "e.jpg", "f.jpg", "g.jpg"];

//create a function named displayImage
//it should not have any values passed into it

function displayImage(){

    //the first statement should generate a random number in the range 0 to 6 (the subscript values of the image file names in the imagesArray)
    var num = Math.floor(Math.random() * (imagesArray.length+1)); // 0...6
    //the second statement display the random image from the imagesArray array in the canvas image using the random number as the subscript value
    document.canvas.src = imagesArray[num];
}

&lt;html&gt;&lt;script&gt; 是 HTML 标记的标签。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多