2017-11-19 13 views
0

임의의 배열에 이미지를 추가하려고합니다. 기본적으로이 무작위 제너레이터는 어떤 영화를보아야하는지 알려주고 제목 아래에 움직이는 이미지를 추가하는 방법을 알아 내려고합니다. 아마도 가장 좋은 방법은 이미지 URL이있는 두 번째 배열을 만들고 + 및 대괄호를 사용하여 기존 배열에 추가하는 것일 수 있습니다. 이미지를로드하는 스크립트를 얻는 방법을 모르겠습니다.이미지 URL 배열을 만들고 기존 배열에 추가하고 jQuery를 사용하여 이미지를로드 할 페이지를 얻으려면 어떻게해야합니까?

<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; 
} 

답변

0

당신이 원하는 것을 달성하기 위해 가장 쉬운 방법은 배열에 문자열이 아닌 객체를 저장하는 것입니다 https://codepen.io/McComb/pen/qVPOQO

HTML : 여기 내 codepen입니다.

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 
); 

이 당신의 HTML에 img 요소를 추가하고 그것을 ID picture을 제공 : 그런 식으로, 그렇게 같은 title 필드와 imageUrl 필드가 객체를 생성 할 수 있습니다. 당신의 JS, 당신은 다음처럼 영화의 제목과 이미지를 설정할 수 있습니다 : 나는 당신의 제안 된 변경 here을 codepen 수정 한

document.getElementById("message").innerHTML=random.title; 

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

.