【问题标题】:Why am I getting this unexpected string error?为什么我会收到这个意外的字符串错误?
【发布时间】:2019-03-18 21:11:12
【问题描述】:

我正在学习 css + js + html rn,在制作一个简单的弹出消息脚本时,我开始在以下脚本中收到意外的字符串错误:

function myFunction() {
  var xbg = prompt("Please enter your name!", "Henry Phillips");
  if (person === null || person == "")
  {
    txt= "Enter your name in the field.";
  } else {
    txt "Hello" + xbg + "! How are you today?"
  }
  document.getElementById("demo").innerHTML = txt;
}

正如控制台所说,字符串错误专门位于此处: line

【问题讨论】:

  • 您在此处缺少= 符号:txt = "Hello" + xbg + "! How are you today?"
  • 看起来你在 else 部分忘记了等号
  • 您缺少= 符号。
  • 没想到,确实……
  • 错误消失了,但由于某种原因没有弹出消息:L

标签: javascript string syntax-error


【解决方案1】:

您的脚本中有一些错误。

首先你忘记了 else 语句中的 =

txt = "Hello " + xbg + "! How are you today?"
----^

if条件不测试好变量名,可以用xbg替换person。

if (xbg === null || xbg == "")
// or shorter
if (xbg && xbg.trim())

最后,如果用户不输入此名称,您就不会再次调用您的脚本。您可以使用setTimeout 给用户一些时间来阅读消息,然后再打开提示。

setTimeout(myFunction, 500);

查看下面的完整固定代码

function myFunction() {
  var xbg = prompt("Please enter your name!", "");
  if (xbg === null || xbg == "")
  {
    txt = "Enter your name in the field.";
    setTimeout(myFunction, 500);
  } else {
    txt= "Hello " + xbg + "! How are you today?"
  }
  document.getElementById("demo").innerHTML = txt;
}

myFunction();
<span id="demo"></span>

【讨论】:

  • 错别字的答案通常会被否决,因为 OP 无法删除带有已投票答案的问题
  • 但是这个操作中有3个错误,不仅仅是错字答案。感谢您提供此信息!
  • 脚本中没有任何不容易发现的错误,例如按 F12 并查看控制台。所以这个问题真的不值得留给未来的访客。您的答案是少数几个也解决了逻辑错误的答案之一 - 逻辑错误也是一个非常简单的初学者错误,可以在 cmets 中解释,因此 OP 可以删除问题
【解决方案2】:

function myFunction() {
  var person = prompt("Please enter your name!", "Put Your Name");
  if (person.trim()) {
    txt = "Hello, " + person + "! How are you today?"
  } else {
    txt = "Enter your name in the field.";
  }

  document.getElementById("demo").innerHTML = txt;
}

myFunction();
<div id="demo"></div>

您可以在此处找到编辑后的脚本。

【讨论】:

  • 之前是不同的,我编辑过,但之前的也可以。
【解决方案3】:

所以基本上你这里有一个错字:用 xbg 改变 person

function myFunction() {
  var xbg = prompt("Please enter your name!", "Henry Phillips");
  if (xbg === null || xbg == "")
  {
    txt= "Enter your name in the field.";
  } else {
    txt ="Hello" + xbg + "! How are you today?"
  }
  document.getElementById("demo").innerHTML = txt;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多