我的 JavaScript 函数由于某种原因无法正常工作

My JavaScript function is not working for some reason

出于某种原因,此功能无法正常工作并且不会弹出警告框,但我的代码与另一个正常运行的页面完全相同。我是不是漏掉了什么蠢东西?

<!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>

应该是..

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

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

你似乎把引号搞砸了。

为您解决了这个问题:

<!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. alert("My name is"+" "+first+" "+last); // missing "+" before "first"

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

onclick="whatsMyName()"

两个错误:

变化: <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);

您需要在“..”中编写函数,并更改alert..如下

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>