img标签中的onclick功能

时间:2015-01-05 11:14:33

标签: javascript-events

我正在尝试使图像可点击,当我们点击图像时,将调用touchRock()函数并相应地更改图像。 这是代码:

<tittle> iRock - The Virtual Pet </tittle>
    <script type ="text/JavaScript">
    function touchRock(){
        var userName = prompt("What is ur userName??" , "Enter name here .");

        if (userName != null){
            alert("It is good to meet you " + userName + "."};
            document.getElementId("rockImg").src="joker.jpg";


        }
    }
    </script>

</head>

<body onload = "alert('hello, I am ur pet rock');">
    <div style "margin-top:400px; text-align:center">
    <img id="rockImg" src="irock.jpg" alt="iRock" style="cursor:pointer" onclick="touchRock();"/>





    </div>
</body>

请帮帮我。

1 个答案:

答案 0 :(得分:1)

你应该使用document.getElement ID,而不是document.getElementId。 你在

中有语法错误

提醒(&#34;很高兴见到你&#34; +用户名+&#34;。&#34; } ;

试试这个:

<html>
<head>
    <tittle> iRock - The Virtual Pet </tittle>
    <script type ="text/JavaScript">
        function touchRock(){
            var userName = prompt("What is ur userName??" , "Enter name here .");

            if (userName != null){
                alert("It is good to meet you " + userName + ".");
                document.getElementById("rockImg").src="joker.jpg";


            }
        }
    </script>
</head>
<body onload="alert('hello, I am ur pet rock');">
    <div style "margin-top:400px; text-align:center">
        <img id="rockImg" src="irock.jpg" alt="iRock" style="cursor:pointer" onclick="touchRock();"/>
    </div>
</body>
</html>