我一直在努力运行这段代码,但不幸的是它似乎没有用;它说
未捕获的TypeError:无法读取
的属性value
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>
答案 0 :(得分:2)
编辑:
document.write
覆盖了身体中的所有内容,在概念上也是非常糟糕的表现。至于在"Hello"
中包装cname
和变量document.createTextNode
,我这样做是为了将原始字符串类型转换为实际的DOM字符串。最后,这个 DOM字符串被附加到body元素。
关于这个很酷的事情是你可以选择你想要添加内容的元素。
试试这个:
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>
答案 1 :(得分:1)
打印你好之后你的页面DOM被重新加载,其中没有文本字段,这就是为什么它不起作用尝试下面的一个代码
function f1()
{
var cname = document.getElementById("user_name").value;
document.write("Hello "+cname);
}
答案 2 :(得分:1)
此代码document.write("Hello")
正在替换您的整个HTML,因此ID user_name
的输入元素正在丢失。
Document.write()
document.write
写入文档流,在已关闭(加载)的文档上调用document.write会自动调用document.open,这将清除文档。
您可以删除该行代码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));
}
&#13;
<!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>
&#13;