代码之家  ›  专栏  ›  技术社区  ›  Michael McComb

如何创建一个图像URL数组,将其附加到现有数组中,并使用jQuery获取页面以加载图像?

  •  0
  • Michael McComb  · 技术社区  · 8 年前

    我正在尝试将图像添加到我的随机数组中。基本上,这个随机生成器告诉你应该看哪部电影,我想知道如何在标题下添加移动的图像。我认为最好的方法可能是使用图像URL创建第二个数组,并使用+和括号将其附加到现有数组中。我只是不知道如何让脚本加载图像。这是我的密码笔: https://codepen.io/McComb/pen/qVPOQO

    HTML

    <head>  
    <link 
    href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
    awesome.min.css" 
    rel="stylesheet"  type='text/css'>  
    <h1 style="text-align: center; color: red; font-family: verdana; font-
    weight: bold;">WHAT CHRISTMAS MOVIE SHOULD I WATCH?</h1>
    </head>
    <body>
    <div class="container">
    <div id="generator" style="padding-top: 10px;">
    <p>
    <i class="fa fa-snowflake-o fa-5x spin"></i>
    <i class="fa fa-gift fa-5x spin"></i>
    <i class="fa fa-tree fa-5x spin"></i>
    
    </p>
    
    <input type="button" id="btnSearch" value="What Christmas Movie Should I 
    Watch?" onclick="GetValue();" />
    <p id="message"></p>
    </div>
    <div id="picture"></div>
    </div>
    

    JQuery

     function GetValue()
    {
    var myarray= new Array("The Santa Claus", "Just Friends","Home Alone", "Home 
    Alone 2","Serendipity","Love Actually","Elf","Christmas Vacation","A 
    Christmas Story","The Grinch","Jingle All the Way","Rudolph the Red-Nosed 
    Reindeer","Ernest Saves Christmas","Frosty the Snowman","The Muppet 
    Christmas Carol","The Nightmare Before Christmas","Jesus of Nazareth 
    1977","Bad Santa");
    var random = myarray[Math.floor(Math.random() * myarray.length)];
    //alert(random);
    document.getElementById("message").innerHTML=random;
    }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Christian Santos    8 年前

    实现所需功能的最简单方法是保存对象,而不是数组中的字符串。这样,您可以创建具有 title 字段和an imageUrl 类似这样的字段:

    var myarray= new Array(
        {
            title: "The Santa Claus",
            imageUrl: "https://upload.wikimedia.org/wikipedia/en/thumb/e/e7/Video-x-generic.svg/90px-Video-x-generic.svg.png"
        }, 
        {
            title: "Random Movie",
            imageUrl: "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ad/BolexH16.jpg/220px-BolexH16.jpg"
        }, 
        // you can add as many comma-separated objects as you want
    );
    

    添加 img 元素并为其指定id picture . 在JS中,您可以这样设置电影的标题和图像:

    document.getElementById("message").innerHTML=random.title;
    
    // the element with id picture is an image element
    document.getElementById("picture").src = random.imageUrl;
    

    我修改了你的密码笔 here 随着提议的变化。