【问题标题】:Trying to put input from a textfield in the console, page just goes blank试图从控制台中的文本字段输入输入,页面只是空白
【发布时间】:2018-11-22 02:00:07
【问题描述】:

我正在尝试编写一个简单的程序。我在 textfeild 中写入文本,单击提交,它会显示在控制台中。听起来很简单,对吧?我也是这么想的。不幸的是,当我点击提交时,页面只是空白。没有错误,它只是空白。为什么会这样?即使将提交按钮更改为常规的通用按钮也不起作用。

这是我的代码:

function write(){
  var graffiti = document.getElementById("graffiti").value; 
  console.log(graffiti);
}
<!DOCTYPE html>
<html>
  <head>
    <script src="graffiti.js"></script>
  </head>
  <body>
    <input type="text" id="graffiti"><br>
    <input type="submit" value="submit" onclick="write()">
  </body>
</html>

怎么了?

【问题讨论】:

  • 尝试添加 e.preventDefault() 可能吗?
  • 我到底是如何以及在哪里放的?
  • 在 write() 方法的第一行
  • function write(e) {} 并在第一行添加e.preventDefault();
  • 好吧,我就是这么做的。还是我也需要在 html 中加入“e”?

标签: javascript html input textfield


【解决方案1】:

试试下面的方法

<!DOCTYPE html>
<html>
  <head> </head>
  <body>
      <input type="text" id="graffiti" /><br />
      <input id="myBtn" type="submit" value="submit" />

    <script>
        function write() {
          var graffiti = document.getElementById("graffiti").value;
          console.log(graffiti);
        }

        document.getElementById("myBtn").addEventListener("click", write);
      </script>
  </body>
</html>

理论因为这个例子不起作用example

我们在 onclick 上传递的函数的名称不起作用。 我认为它会让你与 document.write document.write 的 glocal 定义发生冲突

将 write() 重命名为 myFunction()。

<!DOCTYPE html>
<html>
  <head> </head>
  <body>
        <input type="text" id="graffiti"><br>
        <input id="dasd" type="submit" value="submit" onclick="myFunction()">

    <script>
        function myFunction($event){
            var graffiti = document.getElementById("graffiti").value;
            console.log(graffiti);        
        }
    </script>
  </body>
</html>

我留下一个有趣的链接

【讨论】:

  • 成功了,谢谢。但我仍然希望我知道为什么另一个人不知道。
  • 疯了!!当您调用 onclick 事件时,它的工作方式与您按函数名称所做的方式不同,我认为它会与 document.write w3schools.com/jsref/met_doc_write.asp rename write() 的 glocal 定义冲突/跨度>
猜你喜欢
  • 1970-01-01
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 1970-01-01
  • 1970-01-01
  • 2014-04-14
相关资源
最近更新 更多