Jquery按钮从数组中获取随机图像

时间:2016-08-18 12:30:34

标签: jquery arrays button random

使用jquery,我在codepen上需要帮助。

我评论了我需要帮助的部分,有人可以解释一下我点击按钮后如何在img上显示随机图像

我的代码:

$('#switch').on('click',function(){
  //Help with this part 
  $('h1').html("I'm supposed to switch the picture but I can't do that"); 

我需要#switch(按钮)将#duck(image)src从我提供的数组中更改为随机src。

CodePen link

3 个答案:

答案 0 :(得分:0)

您必须设置img标记的src属性,如下所示。

$("img").attr('src', 'http://example.com/smith.gif') 

答案 1 :(得分:0)

您的switch点击处理程序应如下所示:



$('#switch').on('click', function () {
  $('h1').html("I'm supposed to switch the picture but I can't do that"); //Help with this part 
  $(".content").find("img").attr("src", myArray[Math.floor(Math.random() * myArray.length -1)]);
});




答案 2 :(得分:0)

有问题,你初始化随机变量globaly.I刚刚通过改变这个来定义它的运行时间

$('#duck').attr('src', myArray[Math.floor(Math.random() * myArray.length)]);

还删除了主要类点击事件,因为它不是必要的。更新链接

http://codepen.io/anon/pen/LkvPRq