在页面加载时显示随机图像以及相关的文本标题

时间:2018-04-17 10:11:56

标签: javascript html

我正在尝试创建一个相当简单的JavaScript片段,每次页面加载时都会从数组中显示一个随机图像,然后将相关的文本块作为每个图片的标题显示。我需要弄清楚如何在不向body标签添加代码的情况下运行此方法。有没有办法在没有放置在body标签中的onload函数的情况下完成此操作?

这就是我所依赖的onLoad:

<html>
<head/>
<title>Test</title>
<script type="text/javascript">
  var imageUrls = [
       "http://ww.example.com/image-01.jpg"
     , "http://ww.example.com/image-02.jpg"
     , "http://ww.example.com/image-03.jpeg"
  ];
 var imageLinks = [
       "http://ww.example.com/yoga/"
     , "http://ww.example.com/self-hypnosis/"
     , "http://ww.example.com/herbalism/"
  ];
 var imageText = [
       "Click here to enjoy your Yoga class."
     , "Click here to enjoy your Self-Hypnosis class."
     , "Click here to enjoy your Herbalism class."
  ];

  function getImageHtmlCode() {
    var dataIndex = Math.floor(Math.random() * imageUrls.length);
    var img = '<a href=\"' + imageLinks[dataIndex] + '"><img src="';        
    img += imageUrls[dataIndex];
    img += '\" alt=\"Some alt text\"/></a>';
    return img;
  }
</script>
</head>
<body bgcolor="white">
<script type="text/javascript">
  document.write(getImageHtmlCode());
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

如果您想在图像下方显示文字,只需添加一个范围:

    <html>
<head>
<title>Test</title>
<script type="text/javascript">
    var imageUrls = [
        "http://ww.example.com/image-01.jpg"
      , "http://ww.example.com/image-02.jpg"
      , "http://ww.example.com/image-03.jpeg"
    ];
    var imageLinks = [
        "http://ww.example.com/yoga/"
      , "http://ww.example.com/self-hypnosis/"
      , "http://ww.example.com/herbalism/"
    ];
    var imageText = [
        "Click here to enjoy your Yoga class."
      , "Click here to enjoy your Self-Hypnosis class."
      , "Click here to enjoy your Herbalism class."
    ];

    function getImageHtmlCode() {
      var dataIndex = Math.floor(Math.random() * imageUrls.length);
      var img = '<a href=\"' + imageLinks[dataIndex] + '"><img src="';        
      img += imageUrls[dataIndex];
      img += '\" alt=\"Some alt text\"/></a><span>';
      img += imageText[dataIndex];
      img += '</span>'
      return img;
    }
</script>
</head>
<body bgcolor="white">
<script type="text/javascript">
  document.write(getImageHtmlCode());
</script>
</body>
</html>

这是一个jsfiddle:https://jsfiddle.net/56351syn/11/