简体   繁体   English

单击按钮时如何更改图像?

[英]How to get an image to change when a button is clicked?

I have a div tag which holds an image that is picked at random from a if statement. 我有一个div标签,其中保存有从if语句中随机选择的图像。 My image src are in a number of different arrays sorted via topic. 我的图片src通过主题分类在许多不同的数组中。 What I am having difficulties with is the image changing when my go button is clicked I would like the if statement to repeat giving a new image from a different topic , am I missing something simple here ? 我遇到的困难是单击“ go”按钮时图像发生了变化,我想让if语句从另一个主题重复给出新图像,我在这里遗漏了一些简单的东西吗? I fairly new to javascript so any help would be appreciated. 我对JavaScript相当陌生,因此不胜感激。

The main issue seems to be the way you are trying to replace the existing image. 主要问题似乎是您尝试替换现有映像的方式。

document.write = image;

The previous line replaces the native document.write function with your image markup, wich is obviously not what you want. 前一行用图像标记替换了本机document.write函数,这显然不是您想要的。

Without re-writing all your code , what you could do is find the div that holds the image and replace it's innerHTML property with the content of your image variable. 无需重新编写所有代码 ,您可以做的是找到保存图像的div并将其innerHTML属性替换为image变量的内容。

document.getElementById('div_that_hold_the_image').innerHTML = image;

Please note that if that div contains other children, they will all be removed 请注意,如果该div包含其他子级,则所有这些子级都会被删除

I strongly advise you to read more on JavaScript. 我强烈建议您阅读有关JavaScript的更多信息。 Even tough your code will run, it has plenty of issues that should be adressed. 即使您的代码难以运行,它也有许多应解决的问题。

For instance, you should not rely on global variables to pass data around and you don't need to evaluate a string literal using () before assigning it to a variable. 例如,您不应该依赖全局变量来传递数据,也不需要在将字符串赋给变量之前使用()评估字符串文字。

topic=("Tv Shows"); can just be topic = "Tv Shows"; 可以只是topic = "Tv Shows";

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

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