【问题标题】:How to store string value in javascript after input from textbox从文本框输入后如何在javascript中存储字符串值
【发布时间】:2021-01-21 17:03:38
【问题描述】:

这里是新的 javascript 程序员。我正在尝试创建一个接收用户文本输入的“目标管理器”网络应用程序

      return (
    <>
      <GlobalStyle />
      <StyledH1>Strengthen and stay on top of your goals</StyledH1>
      
      <input id = "text1" placeholder = "New Goal: "/>
  
      <button onclick= "fn1()" id = "btn1"> Set Goal </button>
     
      <script>
        function fn1 () {
        var str = document.getElementById("text1").value;
        alert("Value: " + str);
      }
      </script>
      
      {goals.map((goal) => (
        <Goal
          key={goal.id}
          goal={goal}
          updates={updates.filter(
            (update) => update.fields.goalid[0] === goal.id
          )}
        />
      ))}
    </>
  );
}


我尝试存储使用上述代码输入的值,但遇到了指向 var 的错误“解析错误:意外令牌”。此代码在我的 App.js 文件中的 return () 内。

当我尝试将我的 fn1() 放在 return() 之外时,代码编译,但随后我收到警告“'fn1' is defined but never used”并且代码无法工作,但没有更多var 的问题。

任何帮助将不胜感激!

【问题讨论】:

  • 把你的代码放在一个脚本标签w3schools.com/tags/tag_script.asp
  • 在哪里,在return()里面?我这样做了,但仍然收到意外的令牌错误
  • 我在你的代码中没有看到return()...
  • 抱歉,我刚刚更新了代码以反映正在发生的事情的大局!
  • 看起来您正在将 javascript 和 html 混合在一起。您的 html (

标签: javascript parsing button token getelementbyid


【解决方案1】:

你快到了。 javascript代码应该写在script标签中。

 <input id = "text1" placeholder = "New Goal: "/>
    
     <button onclick= "fn1()" id = "btn1"> Set Goal </button>
      
    <script>
      function fn1 () {
        var str = document.getElementById("text1").value;
        alert("Value: " + str);
      }
    </script>

【讨论】:

  • 这应该在return()里面吗?我仍然收到意外的令牌错误
【解决方案2】:

基本问题是您试图在 app.js 文件中混合使用 html 和 javascript。请在下面找到如何分隔 javascript 和 html 的示例。

<!DOCTYPE html>
<html>
   <head>
      /* This is script and is not mixed with html
         it could also be referred to from a separate file e.g. app.js */
      <script>
         function fn1 () {
           var str = document.getElementById("text1").value;
           alert("Value: " + str);
         }
      </script>
   </head>
   /* This is html and is not mixed with javascript */
   <body>
      <input id = "text1" placeholder = "New Goal: "/>
      <button onclick= "fn1()" id = "btn1"> Set Goal </button>
   </body>
</html>

【讨论】:

  • 感谢 html/javascript 之间的澄清!我仍然收到“解析错误:意外令牌”错误:/ var 有什么问题吗?当我使用 const 或 String 时它不起作用
  • 很难说。我认为您需要发布另一个包含所有修改代码的示例。
猜你喜欢
  • 1970-01-01
  • 2019-06-03
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多