getElementById.value is not working ERROR: form1.html:10 Uncaught ReferenceError: f1 is not defined at HTMLButtonElement.onclick (form1.html:10)

getElementById.value is not working ERROR: form1.html:10 Uncaught ReferenceError: f1 is not defined at HTMLButtonElement.onclick (form1.html:10)

我已经尝试了很多 运行 这段代码,但不幸的是它似乎没有用;它说

Uncaught TypeError: Cannot read property value of null

我注意到 getElementById().value 是罪魁祸首,但是当我 运行 同一个 browser(CHROME, IE, FIREFOX) 上的另一个文件已经在另一台计算机上预先执行时,它打印结果没有错误。

而且 getElementById 几个月前曾经完美地工作。

请帮助我。这真令人沮丧!提前致谢

function f1()
{
 document.write("Hello")

 var cname = document.getElementById('user_name').value;
 document.write(cname);
}
<!DOCTYPE html>
<html>
<head>
 <title>Welcome!</title>
 
</head>
<body>
 
 Enter Name: <input id="user_name" type="text"  /><br/>
 <button onclick="f1()">Click</button>
 
 <script type="text/javascript" src="form1.js"></script>
</body>
</html>

编辑:

document.write overides all content in the body and is also conceptually terrible performance-wise. As for wrapping "Hello" and the variable cname in document.createTextNode, I do so to convert the primitive string type to an actual DOM string. And finally, this DOM string is appended to the body element.

这很酷的一点是,您可以选择要将内容附加到哪个元素。

试试这个:

 function f1() {
   document.body.appendChild(document.createTextNode("Hello "));

   var cname = document.getElementById('user_name').value;
  
   document.body.appendChild(document.createTextNode(cname));
}
<!DOCTYPE html>
<html>
<head>
 <title>Welcome!</title>
 
</head>
<body>
 
 Enter Name: <input id="user_name" type="text"  /><br/>
 <button onclick="f1()">Click</button>
 
 <script type="text/javascript" src="form1.js"></script>
</body>
</html>

打印 hello 后,您的页面 DOM 重新加载,其中文本字段不存在,这就是它不起作用的原因,请尝试下面的一个代码

function f1()
{
    var cname = document.getElementById("user_name").value;
    document.write("Hello "+cname);
}

此代码 document.write("Hello") 正在替换您的整个 HTML,因此 ID 为 user_name 的输入元素将丢失。

Document.write()

document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.

您可以删除那行代码 document.write("Hello") 或按照以下示例操作:

function f1() {
  document.body.appendChild(document.createTextNode("Hello"));

  var cname = document.getElementById('user_name').value;
  document.body.appendChild(document.createTextNode('\n' + cname));
}
<!DOCTYPE html>
<html>

<head>
  <title>Welcome!</title>

</head>

<body>
  Enter Name: <input id="user_name" type="text" /><br/>
  <button onclick="f1()">Click</button>
</body>
</html>