在javaScript中没有调用onClick事件

时间:2013-05-06 19:34:29

标签: 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>

有人可以告诉我这有什么问题吗?因为触摸图像后没有调用事件。

3 个答案:

答案 0 :(得分:7)

函数

中的字符串连接错误

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

Check this

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 - &gt;您将启用开发人员工具栏,因为将有控制台,您可以在其中查看任何错误,调试javascript检查元素等。您可以使用Firebug for FireFox和DevToolbar for Int Explorer。

Script Debugger in Chrome - Ref

答案 1 :(得分:1)

您没有在警报中正确执行字符串连接。

改变这个:

alert("It is good to meet you, " "+userName+ " ".");

对此:

alert("It is good to meet you, " + userName + ".");

要将两个字符串连接在一起,+运算符必须位于字符串之外。

var newString = "I am " + "a concatenated string";

答案 2 :(得分:1)

我认为你可以使用 提醒(&#34;很高兴认识你,&#34; +用户名+&#34;。&#34;);

而不是 提醒(&#34;很高兴认识你,&#34;&#34; +用户名+&#34;&#34;。&#34;);

据我所知,在javascript中我们通常使用&#34; +&#34;连接的符号。