刷新时随机图像

Random Image on Refresh

本文关键字:图像 随机 刷新      更新时间:2023-09-26

我需要一些帮助来修复此代码上的错误:

var image = new Array ();
image[0] = "http://placehold.it/20";
image[1] = "http://placehold.it/30";
image[2] = "http://placehold.it/40";
image[3] = "http://placehold.it/50";
var size = image.length
var x = Math.floor(size*Math.random())
$('#random').attr('src',image[x]);

当我运行HTA(超文本应用程序)时,我得到的错误是:线路:46错误:属性"$"的值为null或未定义,而不是Function对象。第46行是这一行:

$('#random').attr('src',image[x]);

我发现这个代码的问题的链接在这里

编辑

这是我整个程序的代码

有人能帮我吗?

在文件<head>块中添加Jquery库

    <script src="//code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
   <script>
    $(window).load(function(){
    var image = new Array ();
    image[0] = "http://placehold.it/20";
    image[1] = "http://placehold.it/30";
    image[2] = "http://placehold.it/40";
    image[3] = "http://placehold.it/50";
    var size = image.length
    var x = Math.floor(size*Math.random())
    $('#random').attr('src',image[x]);
    });
   </script>

演示

在页面顶部和标题选项卡中包含jquery:

<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>

再试一次:

$(function(){
    var image = new Array ();
    image[0] = "http://placehold.it/20";
    image[1] = "http://placehold.it/30";
    image[2] = "http://placehold.it/40";
    image[3] = "http://placehold.it/50";
    var size = image.length
    var x = Math.floor(size*Math.random())
    $('#random').attr('src',image[x]);
})

试试这个。。希望对有所帮助

 <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(window).load(function(){
    var image = new Array ();
    image[0] = "http://placehold.it/20";
    image[1] = "http://placehold.it/30";
    image[2] = "http://placehold.it/40";
    image[3] = "http://placehold.it/50";
    var size = image.length
    var x = Math.floor(size*Math.random())
    $('#random').attr('src',image[x]);
    });
   </script>

您的代码中有几个错误,下面是一个工作示例。。。

确保jQuery包含在您的页面中

$(document).ready({
   // jQuery has now loaded on the page
   var image = [];
   image[0] = "http://placehold.it/20";
   image[1] = "http://placehold.it/30";
   image[2] = "http://placehold.it/40";
   image[3] = "http://placehold.it/50";
   var src = image[Math.floor(Math.random() * image.length)];
   $('#random').attr('src',src);
});

链接到示例