在javaScript中没有调用onClick事件

Jea*_*ard 2 javascript javascript-events

我正在用javaScript编写我的第一个代码.

我想做这个 :-

  • 加载图像
  • 询问用户名
  • 写完名字后改变图像
  • 并在警报中显示用户的姓名

我的代码是这样的,

<!DOCTYPE html>
<html>
<head>
<title>iRock - First Project</title>
<script type = "text/javascript">

function touchRock(){

    var userName = prompt ("what is your name?","Enter your name here.");

    if(userName){
        alert("It is good to meet you, " "+userName+ " ".");
        document.getElementById("firstImg").src="1.jpg";
    }
}

</script>
</head>

<body onload = "alert('hello, I am your pet.');">
        <div style = "margin-top:100px; text-align:centre">
                 <img id="firstImg" src="http://www.smiley-faces.org/wallpaper/smiley-face-wallpaper-widescreen-001.jpg" alt="iRock" style="cursor:pointer" onclick="touchRock()" />
        </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

谁能告诉我这有什么问题?因为触摸图像后没有调用事件.

PSL*_*PSL 7

函数内部的字符串连接错误

alert("It is good to meet you, " "+userName+ " "."); 你必须在控制台中收到错误.

检查一下

function touchRock(){

    var userName = prompt ("what is your name?","Enter your name here.");

    if(userName){
        alert("It is good to meet you, " + userName +  ".");
        document.getElementById("firstImg").src="1.jpg";
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Chrome.按F12 - >你将启用开发人员工具栏,因为会有控制台,你可以看到任何错误,调试javascript检查元素等.很明显你有FireFug for FireFox和DevToolbar for Int Explorer.

Chrome中的脚本调试程序 - 参考