如何使用事件处理程序 onclick 在 html 上的图像中显示文本

How can I display a text in an image on html using the event handler onclick

<!DOCTYPE html>
<html>

<head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Squares</title>
        <script type="text/javascript">
        function SayColor(color) {
          document.getElementById('message').innerHTML = "You clicked on the " + color + " square!";
        }
        </script>
 </head>

  <body>

    <div style="text-align:center">
    <button onclick="SayColor()> <img src="red-square.png" height="150" width="150" ></button>
    <img src="green-square.png" height="150" width="150"> 
    <img src="blue-square.png" height="150" width="150"> 
    <h3 id="message">
    </h3>
    </div>

</body>
</html>

这是我在代码开头的尝试,我不确定如何完成它。我熟悉事件处理程序但不熟悉函数。我试图在单击时在每个图像框中显示文本 "You clicked on the [color of square] square!"

好的,我看到你正在定义函数,但它需要一些你没有传递的参数。如果您只需要单击,则不需要按钮,就像您可以像下面那样尝试,为图像 dom 元素本身添加事件处理程序。 P.S 你不能将它作为红色传递,因为我们将未定义它,所以在这里传递一个字符串值。

    <!DOCTYPE html>
<html>

<head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Squares</title>
        <script type="text/javascript">
        function SayColor(color) {
          document.getElementById('message').innerHTML = "You clicked on the " + color + " square!";
        }
        </script>
 </head>

  <body>

    <div style="text-align:center">
     <img onclick=SayColor("RED") src="red-square.png" height="150" width="150" >
    <img onclick=SayColor("Green") src="green-square.png" height="150" width="150"> 
    <img onclick=SayColor("Blue") src="blue-square.png" height="150" width="150"> 
    <h3 id="message">
    </h3>
    </div>

</body>
</html>

希望对您有所帮助!编码愉快!