简体   繁体   English

单击按钮上的Javascript随机图像

[英]Javascript random image on click button

I've been following some tutorials on how to randomize an image by setting up an array in Javascript. 我一直在关注如何通过在Javascript中设置数组来随机化图像的一些教程。 It's not working - the image itself is not appearing, not even any error. 它不起作用 - 图像本身没有出现,甚至没有任何错误。

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()"/>

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>

You forgot a ) in your if statement and on your document.write you missed ' and closing the <img> tag. 你忘记了a )你的if语句和你的document.write你错过了'并关闭<img>标签。 Check here: 点击这里:

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

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

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); 如果我是你,我会在你的DOM文档中指出一个更具体的点。你可以使用一个非常简单的jQuery脚本,如果你想要: $("#testing").html(html_code); instead of your document.write() 而不是你的document.write()

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实际上将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! 等等!

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通常不是向页面添加元素的首选方法,但似乎这是一个学习的例子而不是现实世界的例子。

Oh man, this is embarrassing. 哦,伙计,这很尴尬。 Crazy how much you can learn in 3 years. 疯狂你能在3年内学到多少东西。 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. 没有测试但应该工作。

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 if check? 我在考虑将数组分配给[1]然后进行if检查是什么意思? I'll never know. 我永远不会知道。

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 src in the img tag. 这是我能想到的最好的方式,我更喜欢这个,是因为它不是改变整个页面,而是改变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 src for my image. 然而,我所做的是,我有一个空白的png文件,其中没有任何内容,我将其设置为我的图像的默认src But you can do as you please. 但你可以随意做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM