显示已更改的图像标题

Displaying a changed image title

本文关键字:图像 标题 显示      更新时间:2023-09-26

我想把我的图像的标题显示在图像本身的正下方。我在图像中有一个onClick事件,一旦你点击它,它就会改变图像的标题。

<!DOCTYPE html>
<html>
<head>
    <title>
        onClick Handler
    </title>
    <h3 style="text-align:center">onClick Handler</h3>
</head>
<body style="text-align:center">
    <img src="NukaCola.jpg" title="Nuka Cola" id="id1" height="550" width="350" onClick="this.title='You Clicked!';"/>
    </br><script>
        var x=document.getElementById("id1");
        document.write(x.title);
    </script>
</body>
</html>

现在,我知道使用document是不好的形式。write(),它甚至没有完成我想做的事情,因为我想在用户点击图像后显示新的图像标题。我怎样才能做到这一点呢?

<!DOCTYPE html>
<html>
<head>
    <title>
        onClick Handler
    </title>
    <h3 style="text-align:center">onClick Handler</h3>
</head>
<body style="text-align:center">
    <img src=NukaCola.jpg title="Nuka Cola" id="id1" height=550 width=350 onClick="updateTitle(this)"/>
    <p id='id1Text'></p>
    </br>
    <script>
        function updateTitle(img) {
            img.title = 'You clicked!';
            document.getElementById(img.id +'Text').textContent = img.title;
        }
    </script>
</body>
</html>

注意到:在head标签中声明了一个h3标签