javascript 如何显示带有关联图像的随机选择的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17632519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:01:48  来源:igfitidea点击:

How do I display randomly-chosen text with an associated image?

javascriptquotesdynamic-linkingpage-refresh

提问by nastiark

I'm a beginner web designer and I need to know how can I link one thing to another. The thing is that I'm making different quotes change every time the site refreshes. And I need to do the same thing with images that are located in a different div tag. The reason I need to link them is because the image needs to coordinate with the quote. For example: quote 0 with image 0.

我是一名初级网页设计师,我需要知道如何将一件事与另一件事联系起来。问题是每次网站刷新时我都会更改不同的报价。我需要对位于不同 div 标签中的图像做同样的事情。我需要链接它们的原因是图像需要与引用协调。例如:引用 0 和图像 0。

Here is the javascript code:

这是javascript代码:

var quotes=new Array();
quotes[0] = "text1";
quotes[1] = "Text2";
quotes[2] = "text3";
quotes[3] = "text4";

var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){document.write(quotes[whichquote]);}
showquote();

And this is the code that is located the javascript text:

这是位于 javascript 文本的代码:

<script language="javascript" type="text/javascript" src="quotes.js"></script>

回答by T.J. Crowder

Some notes on that code. Don't take these the wrong way, you're new to JavaScript! Everyone was once, having people point things out is one way we learn.

关于该代码的一些注释。不要误会这些,您是 JavaScript 新手!每个人都曾经是,让人们指出事情是我们学习的一种方式。

  1. There's almost never any reason to use new Array. Use an array literal. In this case:

    var quotes = [
        "text1",
        "Text2",
        "text3",
        "text4"
    ];
    
  2. The languageattribute was deprecated in the 90's, and the default value of typeon scriptis text/javascript. So just <script src="..."></script>is all you need.

  3. Your random number is wrong. Math.randomreturns a number from 0(inclusive) to 1(exclusive), so you want to just multiply by the number of images, not the number minus one.

  4. document.writeis best avoided. There's very, very little reason to use it in modern web programming.

  1. 几乎没有任何理由使用new Array. 使用数组文字。在这种情况下:

    var quotes = [
        "text1",
        "Text2",
        "text3",
        "text4"
    ];
    
  2. language属性已被废弃在90年代,和默认值typescripttext/javascript。所以这<script src="..."></script>就是你所需要的。

  3. 你的随机数是错误的。Math.random返回一个从0(inclusive) 到1( exclusive) 的数字,因此您只想乘以图像的数量,而不是数字减一。

  4. document.write最好避免。在现代 Web 编程中使用它的理由非常非常少。

Here's one way to approach doing what you described: Live Example| Live Source

以下是完成您所描述的操作的一种方法:Live Example| 直播源

(You have to refresh it a lot, because it only has two entries, so you have pretty good odds of seeing the same one.)

(您必须经常刷新它,因为它只有两个条目,因此您很有可能看到相同的条目。)

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Random Text Plus Image</title>
</head>
<body>
  <div id="quote"></div>
  <script>
    (function() {
      var quotes = [
        {
          text: "text1",
          img:  "http://i.stack.imgur.com/FqBE6.jpg?s=32&g=1"
        },
        {
          text: "text2",
          img:  "https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=32&d=identicon&r=PG",
        }
      ];
      var quote = quotes[Math.floor(Math.random() * quotes.length)];
      document.getElementById("quote").innerHTML =
        '<p>' + quote.text + '</p>' +
        '<img src="' + quote.img + '">';
    })();
  </script>
</body>
</html>

What I did there:

我在那里做了什么:

  • I output an element, the <div id="quote"></div>, to hold the quote and image. This is instead of the document.write.

  • I used an array literal, but my array literal contains objectliterals (the {...}things with text: "text1"and such in them). So my array contains objects, where each object has the properties text(the text of that quote) and img(the URL of the image to use).

  • I fixed the random thing.

  • When outputting the text (which I assume is HTML markup) and the image, I do that by setting innerHTMLon the quotedivI output above the code.

  • I put all of my code in an enclosing function that I call immediately. This prevents creating any global variables.

  • 我输出一个元素 the<div id="quote"></div>来保存引用和图像。这是而不是document.write.

  • 我使用了一个数组文字,但我的数组文字包含对象文字(其中包含的{...}东西text: "text1")。所以我的数组包含对象,其中每个对象都有属性text(引用的文本)和img(要使用的图像的 URL)。

  • 我修复了随机的东西。

  • 当输出文本(我假设是 HTML 标记)和图像时,我通过在代码上方的 I 输出上进行设置innerHTML来做到这一点quotediv

  • 我把我所有的代码放在一个我立即调用的封闭函数中。这可以防止创建任何全局变量。

Hope this helps.

希望这可以帮助。

回答by MiRaIT

Assuming you have something like the following html:

假设您有类似以下 html 的内容:

<div id="quote"></div>
<div>
    <img class="image" src="http://www.placehold.it/100x50&text=1" />
    <img class="image" src="http://www.placehold.it/100x50&text=2" />
    <img class="image" src="http://www.placehold.it/100x50&text=3" />
    <img class="image" src="http://www.placehold.it/100x50&text=4" />
</div>

and css

和CSS

.image {
   display: none;
}

Then you need to do something like this in your showquotefunction:

然后你需要在你的showquote函数中做这样的事情:

function showquote(){
   document.getElementById('quote').innerHTML = quotes[whichquote];
   document.getElementsByTagName('img')[whichquote].style.display="block";
}

See the fiddle here: http://jsfiddle.net/fYPY7/

请参阅此处的小提琴:http: //jsfiddle.net/fYPY7/