如何在点击按钮时改变图像?

这是我到目前为止所尝试过的,但它不起作用。我试图让按钮在点击时显示不同的图片。


<!DOCTYPE html>

<html>

<head>

<header></header>

<link rel="stylesheet" type="text/css" href="C.css">

<body>


<p> <font face="Times New Roman" size=18> Parakeet Images </font> </p>

<img id="parakeet"  src="green_parakeet.jpg" src="blue_parakeet.jpg" />

<button onclick="g()">Show Green!</button>

<script>function g(){document.getElementById('parakeet').src="green_parakeet.jpg;}</script>

<button onclick="b()">Show Blue!</button>

<script>function b(){document.getElementById('parakeet').src="blue_parakeet.jpg;}</script>

</body>

</html>


POPMUISE
浏览 66回答 3
3回答

大话西游666

您忘记关闭“ :<!DOCTYPE html><html><head><header></header><link rel="stylesheet" type="text/css" href="C.css"><body><p> <font face="Times New Roman" size=18> Parakeet Images </font> </p><img id="parakeet"&nbsp; src="green_parakeet.jpg"&nbsp; /><button onclick="g()">Show Green!</button><script>function g(){document.getElementById('parakeet').src="green_parakeet.jpg";}</script><button onclick="b()">Show Blue!</button><script>function b(){document.getElementById('parakeet').src="blue_parakeet.jpg";}</script></body></html>

MYYA

您的两个脚本中都缺少结束引号<!DOCTYPE html><html>&nbsp; &nbsp;<head>&nbsp; &nbsp; &nbsp; <link rel="stylesheet" type="text/css" href="C.css">&nbsp; &nbsp;</head>&nbsp; &nbsp;<body>&nbsp; &nbsp; &nbsp; <p> <font face="Times New Roman" size=18> Parakeet Images </font> </p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<img id="parakeet"&nbsp; src="green_parakeet.jpg" src="blue_parakeet.jpg" />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<button onclick="g()">Show Green!</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<script>function g(){document.getElementById('parakeet').src="green_parakeet.jpg"}</script>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<button onclick="b()">Show Blue!</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<script>function b(){document.getElementById('parakeet').src="blue_parakeet.jpg"}</script>&nbsp; &nbsp;</body></html>

繁星点点滴滴

您的代码是正确的,只是您在图像名称末尾缺少“并且元素src中有额外的标签img。function b() {&nbsp; document.getElementById('parakeet').src = "https://dummyimage.com/600x400/209de6/fff";}function g() {&nbsp; document.getElementById('parakeet').src = "https://dummyimage.com/600x400/20e62a/fff";}<!DOCTYPE html><html><head>&nbsp; <header></header>&nbsp; <link rel="stylesheet" type="text/css" href="C.css">&nbsp; <body>&nbsp; &nbsp; <p>&nbsp; &nbsp; &nbsp; <font face="Times New Roman" size=18> Parakeet Images </font>&nbsp; &nbsp; </p>&nbsp; &nbsp; <img id="parakeet" src="https://dummyimage.com/600x400/20e62a/fff" />&nbsp; &nbsp; <button onclick="g()">Show Green!</button>&nbsp; &nbsp; <button onclick="b()">Show Blue!</button>&nbsp; </body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript