单击javascript按钮时添加媒体

时间:2017-08-18 09:42:32

标签: javascript html css

我创建了一个JS按钮,可以在单击时生成随机事实。 现在我希望每个String(事实)都有下面的媒体,以使事实更有趣和有趣。

<script> <!-- arrays -->function GetValue(){ var myarray= new Array()
myarray[0]="your lungs are worth $58,200 each,heart will fetch $57,000, and your kidneys are good for another $91,400,your DNA will fetch more than 9M$,while your bone marrow, your most valuable possession, is worth $23 million all by itself. Therefore your body market value is exactly: $45,618,575.82." 
myarray[1]="Hans Langseth the man with the world's longest beard 5.33 m (17 ft 6 in)tripped on his long beard. He lost his balance and fell, breaking his neck from the unexpected accident! He died instantaneously."
myarray[2]="A Sesame Street episode (ep. 847) was aired on TV in 1976,it was so scary that the authorities had to pull it off due to several complaints from parents saying their children screamed in horror."<!--END-var random = myarray[Math.floor(Math.random() * myarray.length)];//alert(random); document.getElementById("fact button").innerHTML=random;}</script>

HTML:

<input  type="button" id="fact_button" value="Fact Button" onclick="GetValue();" />

1 个答案:

答案 0 :(得分:0)

假设你想要显示像图像这样的媒体,这是一种方法:

window.onload = () => {
    const factsArr = [
      {
        image: 'http://via.placeholder.com/350x150',
        content: "your lungs are worth $58,200 each,heart will fetch $57,000, and your kidneys are good for another $91,400,your DNA will fetch more than 9M$,while your bone marrow, your most valuable possession, is worth $23 million all by itself. Therefore your body market value is exactly: $45,618,575.82."
      },
      {
        image: 'http://via.placeholder.com/200x140',
        content: "Hans Langseth the man with the world's longest beard 5.33 m (17 ft 6 in)tripped on his long beard. He lost his balance and fell, breaking his neck from the unexpected accident! He died instantaneously."
      },
      {
        image: 'http://via.placeholder.com/200x100',
        content: "A Sesame Street episode (ep. 847) was aired on TV in 1976,it was so scary that the authorities had to pull it off due to several complaints from parents saying their children screamed in horror."
      }
    ];
  
    
    document.getElementById('generate-btn').addEventListener('click', () => {
      const idx = Math.floor(Math.random() * factsArr.length);
      document.getElementById('random-fact-content').innerHTML = factsArr[idx].content;
      document.getElementById('random-fact-image').setAttribute('src', factsArr[idx].image)
    })
      
}
<button id="generate-btn">Generate Random Fact</button>
<div id="random-fact-content"></div>
<img id="random-fact-image"></img>