我的JavaScript函数由于某种原因不起作用

时间:2015-04-04 06:45:32

标签: javascript function alert

由于某种原因,此功能无法正常工作且警报框没有弹出,但我的代码与另一个有效的页面相同。我在这里错过了一些愚蠢的东西吗?

<!DOCTYPE html>
<html>
<head>
  <title>What's my name?</title>
  <script>
    function whatsMyName() {
        var first = "firstname";
        var last = "lastname";
        alert("My name is"+" "first+" "+last);
    }
  </script>
</head>
<body>
  <button type="button" onclick=whatsMyName()>What's my name?</button>
  <br><br>
  <a href="index.html">Return</a>
</body>
</html>

5 个答案:

答案 0 :(得分:3)

你好像搞砸了很多报价。

修正了你:

<!DOCTYPE html>

<html>
<head>
  <title>What's my name?</title>
  <script>
    function whatsMyName() {
        var first = "Corey";
        var last = "LeBlanc";
        alert("My name is " + first + " " + last);
    }
  </script>
</head>
<body>
  <button type="button" onclick="whatsMyName();">What's my name?</button>
  <br><br>
  <a href="index.html">Return</a>
</body>
</html>

答案 1 :(得分:2)

的变化:

  1. alert("My name is"+" "+first+" "+last); // missing "+" before "first"

  2. <button type="button" onclick="whatsMyName()">What's my name?</button>

  3. 的onclick = “whatsMyName()”

答案 2 :(得分:1)

应该是......

<button type="button" onclick="whatsMyName()">What's my name?</button>

alert("My name is"+" "+first+" "+last);

答案 3 :(得分:0)

两个错误:

变化: <button type="button" onclick=whatsMyName()>What's my name?</button>

要: <button type="button" onclick="whatsMyName()">What's my name?</button>

变化: alert("My name is"+" "first+" "+last);

要: alert("My name is"+" "+first+" "+last);

答案 4 :(得分:0)

您需要在&#34; ..&#34;中编写功能。并改变警告......如下所示

alert("My name is" + " " +first+ " " +last); 

<body>
  <button type="button" onclick = "whatsMyName()">What's my name?</button>
  <br><br>
  <a href="index.html">Return</a>
</body>