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

My JavaScript function is not working for some reason

本文关键字:工作 函数 JavaScript 我的 由于某种原因      更新时间:2023-09-26

由于某些原因,此函数不起作用,警报框也不会弹出,但我的代码与另一个起作用的页面完全相同。我是不是错过了什么愚蠢的东西?

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

您似乎把引号搞得一团糟。

为您修复了这个问题:

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

也称为CCD_ 3;

您需要在".."中编写函数,并更改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>

两个错误:

更改:<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);