我试图帮助一位朋友制作他的网站学校项目,但遇到了问题。它本来应该有 3 个文本框,其中一个按钮可以添加更多文本框,我尝试过,document.write但它覆盖了整个页面,所以我查了一下,发现了document.createElement,这似乎不太有效。
我不知道我的代码中是否有任何错误。
<!DOCTYPE html>
<html>
<head>
<style>
.input {
margin-top: 50px;
}
.input .submit {
float: left;
}
.add {
margin-left: 100px;
margin-top: 50px;
width: 50px;
height: 50px;
font-size: 30px;
}
.gen {
float: right;
margin-right: 100px;
width: 400px;
height: 50px;
font-size: 25px;
}
.output {
position: fixed;
margin-top: 100px;
float: right;
margin-left: 400px;
}
</style>
<script language="javascript" type="text/javascript">
var input = document.createElement("<p>Hello</p>");
var container = document.getElementsByClassName("buttons");
container.appendChild(input);
</script>
</head>
<body>
<form class="buttons">
<input type="text" class="input">
<input type="submit" class="submit">
<br>
<input type="text" class="input">
<input type="submit" class="submit">
<input type="button" class="gen" value="Click to generate a random word">
<input type="text" class="output">
<br>
<input type="text" class="input">
<input type="submit" class="submit">
<br>
</form>
<input type="button" class="add" value="+" >
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
您传递的参数不正确document.createElement- 此方法的文档可以在此处找到:document.createElement
document.createElement接受标签名称,但您必须通过对象操作添加其他属性。
var p = document.createElement("p");
p.textContent = "Hello";
document.body.appendChild(p);
Run Code Online (Sandbox Code Playgroud)
其次,您使用的var container = document.getElementsByClassName("buttons")也是不正确的。您正在尝试获取容器元素,但要求它获取类名为“buttons”的元素列表。这将返回一个数组,并要求您选择返回的第一个选项,例如container[0].appendChild
事实上,您应该使用 ID 而不是类名。ID 旨在是唯一的,以便可以在文档中轻松找到单个元素,类名称旨在用于更改多个元素。不过,考虑到您的情况,您应该更改初始查询,以便它只返回单个元素document.querySelector(".buttons")
var container = document.querySelector(".buttons");
Run Code Online (Sandbox Code Playgroud)
全部一起:
var p = document.createElement("p");
p.textContent = "Hello";
document.body.appendChild(p);
Run Code Online (Sandbox Code Playgroud)
var container = document.querySelector(".buttons");
Run Code Online (Sandbox Code Playgroud)
一句建议:从您在此处提供的代码来看,您可能不太了解该语言,无法帮助向其他人教授该语言。这并不是说你没有资质或能力,但看来你需要花更多时间研究材料才能达到这一点。