javascript 单击按钮上的Javascript随机图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17933158/
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 10:09:47  来源:igfitidea点击:

Javascript random image on click button

javascripthtml

提问by Alexander Lozada

I've been following some tutorials on how to randomize an image by setting up an array in Javascript. It's not working - the image itself is not appearing, not even any error.

我一直在关注一些关于如何通过在 Javascript 中设置数组来随机化图像的教程。它不起作用 - 图像本身没有出现,甚至没有任何错误。

JavaScript

JavaScript

<script type="text/javascript">
    function randomImg1(){
        var myImages1 = new Array ();
        myImages1[1] = "img/who/1.jpg";
        myImages1[2] = "img/who/2.jpg";
        myImages1[3] = "img/who/3.jpg";
        var rnd = Math.floor(Math.random() * myImages1.length);
        if(rnd == 0{
            rnd = 1;
        }
        document.write(<img class="who" src="'+myImages1[rnd]);
    }
</script>

and my button looks like this

我的按钮看起来像这样

<input class="randombutton" style="float: left;" type="button" value="Randomize" onclick="randomImg1()"/>

采纳答案by Alexander Lozada

Oh man, this is embarrassing. Crazy how much you can learn in 3 years. I think the most optimal way of doing this would be the following (assuming there is no folder structure pattern). Haven't tested but should work.

哦,伙计,这很尴尬。疯狂的是你可以在 3 年内学到多少。我认为这样做的最佳方法如下(假设没有文件夹结构模式)。尚未测试,但应该可以工作。

var images = ["img/who/1.jpg","img/who/2.jpg","img/who/3.jpg"];

function getRandomImage(){
    var rnd = Math.floor(Math.random() * images.length);
    return images[rnd];
}

function changeImage(){
    var img = document.querySelector("#myImg");
    img.src = getRandomImage();
}

function init(){
    var el = document.querySelector(".myClass");
    el.onclick = changeImage;
}

window.onload = init;

What was I thinking assigning an array to [1]and then doing an ifcheck? I'll never know.

我在想将一个数组分配给什么[1]然后进行if检查?我永远不会知道。

回答by Sergio

You forgot a )in your if statement and on your document.write you missed 'and closing the <img>tag. Check here:

您忘记了)if 语句和文档中的a 。写下您错过了'并关闭了<img>标签。检查这里:

if (rnd == 0) {
        rnd = 1;
    }

document.write('<img class="who" src="' + myImages1[rnd] + '"/>');

回答by rorofromfrance

Make sure to keep track of all your closing brackets and parenthesis.

确保跟踪所有的结束括号和括号。

This code will work for you:

此代码将为您工作:

<script type="text/javascript">
    function randomImg1() {
      var myImages1 = new Array ();
      myImages1[1] = "img/who/1.jpg";
      myImages1[2] = "img/who/2.jpg";
      myImages1[3] = "img/who/3.jpg";
      var rnd = Math.floor( Math.random() * myImages1.length );
      if( rnd == 0 ) {
        rnd =1;
      }
      html_code = '<img class="who" src="' + myImages1[rnd] + '" />";
      document.write(html_code);
    }
</script>

Also if I were you, I would point to a more specific point in your DOM document.. You could use a very simple jQuery script like this if you want: $("#testing").html(html_code);instead of your document.write()

另外,如果我是你,我会在你的 DOM 文档中指出一个更具体的点。如果你愿意,你可以使用一个非常简单的 jQuery 脚本:$("#testing").html(html_code);而不是你的document.write()

回答by innoprog

To APPEND something in your page to an element in the HTML, use

要将页面中的某些内容附加到 HTML 中的元素,请使用

.append

rather than the "write" function, as .append will actually APPEND content to a specified element, rather than all over your whole DOCUMENT.

而不是“写入”函数,因为 .append 实际上会将内容附加到指定的元素,而不是整个文档。

So, in your HTML, you should create a DIV with ID "our_div"

因此,在您的 HTML 中,您应该创建一个 ID 为“our_div”的 DIV

<html>
<head></head>
<body>
<!-- Text will be appended to this DIV via JS -->
<div id="the_div">Hello, </div>
</body>
</html>

Use something like this:

使用这样的东西:

function add_text() {
  $("#the_div").append("World"); // appends text "World" to the end of that div.
}

Now, inside your HTML, you should have a button that calls the function "add_text()".

现在,在您的 HTML 中,您应该有一个调用函数“add_text()”的按钮。

<button id="the_button" onClick="add_text();">Click Here to Add Text</button>

Now then!

接着!

When a user clicks the button, it will append the text "World" to the DIV with ID "the_div..." THUS, we have...

当用户单击按钮时,它会将文本“World”附加到 ID 为“the_div...”的 DIV 中,因此,我们有...

Hello, World

Here's the entire code:

这是整个代码:

<html>
<head>
<script type="text/javascript">
function add_text() {
  $("#the_div").append("World");
}
</script>
</head>
<body>
<div id="the_div">
Hello, 
</div>
<button id="the_button" onClick="add_text();">Click!</button>
</body>
</html>

Try using

尝试使用

.html

to REPLACE something... For example, I use a Dice Roll Function in a game I have developed. When a player rolls the dice...

替换某些东西...例如,我在我开发的游戏中使用了掷骰子功能。当玩家掷骰子...

$("#results").append(Math.floor(Math.rand()*6));

gives us something like this...

给了我们这样的东西......

(every roll)

(每卷)

results: 142563342515246422

and if I use .html...

如果我使用 .html ...

$("#results").html(Math.floor(Math.rand()*6));

we are left with something more like this

我们留下了更像这样的东西

(first roll)

(第一卷)

results: 5

(second roll)

(第二卷)

results: 2

(third roll)

(第三卷)

results: 6

And so on!

等等!

回答by amatellanes

You have to add quotes in this line and close the if statement:

您必须在此行中添加引号并关闭 if 语句:

<script type="text/javascript">
function randomImg1() {
    var myImages1 = new Array();
    myImages1[1] = "img/who/1.jpg";
    myImages1[2] = "img/who/2.jpg";
    myImages1[3] = "img/who/3.jpg";
    var rnd = Math.floor(Math.random() * myImages1.length);
    if (rnd == 0) {
            rnd = 1;
    }
    document.write('<img class="who" src="' + myImages1[rnd] + '">');
}
</script>

回答by Ted A.

The HTML you are writing to your document is incomplete.

您写入文档的 HTML 不完整。

You need something like:

你需要这样的东西:

document.write("<img class='who' src='" + myImages1[rnd] + "'>");

I would also caution that document.write is not normally a preferred method of adding elements to the page, but it seems that this is more a learning example than a real world example.

我还要提醒的是,document.write 通常不是向页面添加元素的首选方法,但似乎这更像是一个学习示例而不是现实世界的示例。

回答by user263885

This is the best way I can think of, the reason I prefer this, is because instead of changing the whole page, it just changes the srcin the imgtag.

这是我能想到的最好的方法,我更喜欢这个的原因是因为它不是改变整个页面,而是改变了img标签中的src

Here's the code:

这是代码:

Script

脚本

function imgchange() {

var myImages1 = new Array();
    myImages1[1] = "img/who/1.jpg";
    myImages1[2] = "img/who/2.jpg";
    myImages1[3] = "img/who/3.jpg";
  var rnd = Math.floor(Math.random() * myImages1.length);
    if (rnd == 0) {
            rnd = 1;
    }

  document.getElementById("gen-img").src = myImages1[rnd];

}

Html

html

<p><img id="gen-img" src="img/who/1.jpg"></p>
<p><input type="button" value="Random" onclick="imgchange();" /></p>

What I do however, is I have a blank png file with nothing in it, and I set that as the default srcfor my image. But you can do as you please.

然而,我所做的是我有一个空白的 png 文件,里面什么都没有,我将它设置为我的图像的默认src。但你可以随心所欲。