我正在用 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>
谁能告诉我这有什么问题吗?因为在触摸图像后不会调用该事件。
最佳答案
函数内部的字符串连接错误
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";
}
}
如果您使用的是 Chrome。按 F12 --> 您将启用开发人员工具栏,因为会有一个控制台,您可以在其中查看任何错误、调试 javascript 检查元素等。同样,您有 FireFox 的 Firebug 和 Int Explorer 的 DevToolbar。
关于javascript - onClick 事件没有在 javaScript 中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16405888/