我正在尝试创建一个JavaScript,该JavaScript将显示3个按钮,并且每个按钮将基于该按钮显示不同的图像。以下是到目前为止的内容。问题是我只显示3个按钮,但是当我单击该按钮以显示图像时却没有任何动作。谢谢您的帮助。
<script type = "text/javascript">
function pic1()
{
document.getElementById("png").src = "C:\Users\aj\Desktop\Red Light.png";
}
function pic2()
{
document.getElementById("png").src ="C:\Users\aj\Desktop\Green Light.png";
}
function pic3()
{
document.getElementById("png").src = "C:\Users\aj\Desktop\Yellow Light.png";
}</script>
<img src = "" id = "png "/> <input type="button" value= "Red Light" onclick="pic1()"/>
<input type="button" value="Green Light" onclick="pic2()"/> <input type="button" value="Yellow Light" onclick="pic3()"/>
答案 0 :(得分:0)
从您的<img src="" id="png" />
值中删除多余空间后,以这种方式进行操作,即png
至png
,否则将导致TypeError: document.getElementById(...) is null
您还可以根据按钮的值将多个功能删除,例如 pic1(),pic2(),pic3()到 pic(this)根据需要设置图像src
(在此示例中,我使用了一些在线演示图像)。希望对您有所帮助:)
<script type="text/javascript">
function pic(param) {
if (param.value === 'Red Light') {
document.getElementById("png").src = "https://is5-ssl.mzstatic.com/image/thumb/Music71/v4/0f/79/15/0f79154d-fe37-001c-be03-51a29d458f22/source/1200x630bb.jpg";
} else if (param.value === 'Green Light') {
document.getElementById("png").src = "https://socialcare.blog.gov.uk/wp-content/uploads/sites/8/2013/12/green-traffic-light-md.png";
} else if (param.value === 'Yellow Light') {
document.getElementById("png").src = "http://www.clker.com/cliparts/8/1/7/4/11949849782053089133traffic_light_yellow_dan_01.svg.med.png";
}
//console.log(param.value)
}
</script>
<img src="" id="png" style="width:30px; height:30px;" />
<input type="button" value="Red Light" onclick="pic(this)" />
<input type="button" value="Green Light" onclick="pic(this)" />
<input type="button" value="Yellow Light" onclick="pic(this)" />