【问题标题】:Jquery button getting a random image from arrayJquery按钮从数组中获取随机图像
【发布时间】:2016-08-18 12:30:33
【问题描述】:

玩 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(button) 将 #duck(image) src 更改为我提供的数组中的随机 src。

CodePen link

【问题讨论】:

  • 发布 HTML,或许还有 PEN 的链接
  • 抱歉,刚刚做了。
  • 先改成<button type="button"

标签: jquery arrays button random


【解决方案1】:

您的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)]);
});

【讨论】:

  • 哇,谢谢,这是我需要的。你能为我解释一下代码吗?为什么数组末尾的 -1 可以使用我定义的变量从数组中获取随机 img 吗?
  • 您应该将random 定义为一个函数,而不是一个变量,因为现在编写的全局变量每次都会返回相同的数字并且没有帮助。 -1 是因为数组是从零开始的 [1, 2, 3] 将在 index 0 有 1,在 index 1 有 2,在 index 2 有 3,而长度为 3,但你不会有index 3 的值,因此是 -1
  • 谢谢玛塔。我将如何创建一个从数组中随机返回字符串的函数?
  • 更通用的函数如下所示:function getRandomArrayItem (array) { return array[Math.floor(Math.random() * (array.length - 1))]; }
【解决方案2】:

你必须像下面这样设置你的 img 标签的 src 属性。

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

【讨论】:

    【解决方案3】:

    有问题因为你初始化了全局随机变量。我刚刚通过更改它定义了它的运行时间

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

    同时删除主类点击事件,因为它不是必需的。请在更新的链接下方尝试

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

    【讨论】:

    • 所以当我想从数组中获取随机字符串/图像时,我必须将其定义为函数而不是变量?
    • 是的,如果你想定义为变量,你需要在函数内部定义它。
    猜你喜欢
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多