我目前正在使用一些 HTML 和 Javascript 来尝试创建评论部分。
基本上,我想要完成的是拥有一个带有文本区域(首选,当您按 Enter 键提交时,Shift+输入新行)或输入类型=文本的表单,以将文本框中的任何内容提交到表单下方的段落(或 div,甚至另一个文本区域)。
|______你好__________| <- 文本框
下面的评论:
Press Enter
|________________| <- 文本框
下面的评论:
你好
<小时/>这是我到目前为止的代码,但它不起作用:
<!DOCTYPE html>
<html>
<head>
<title>Comments Test</title>
<link href="mainstyles.css" rel="stylesheet" />
<script src="mainjs.js"></script>
</head>
<body>
<form>
<input type="text" onsubmit="postComment(this)" />
<p>
Comments Below:
</p>
</form>
</body>
</html>
<小时/>
function postComment(input) {
//Variable for the form
var form = input.parentElement;
//Variable for text input
var inputs = form.getElementsByTagName("input");
//Variable for the value of the form and if condition met "then" do this if true "else" this if false
var response = inputs;
//Variables for creating a paragraph element and text per response
var node = document.createElement("p"),
textNode = document.createTextNode(response);
//Adding the response text to the paragraph and appending that to the bottom of the form
node.appendChild(textNode);
form.appendChild(node);
}
最佳答案
你很接近:
- 将
onsubmit
处理程序移至表单元素。 getElementsByTagName
返回一个集合。要获取输入的值,请使用inputs[0].value
。
片段
function postComment(input) {
//Variable for the form
var form = input.parentElement;
//Variable for text input
var inputs = form.getElementsByTagName("input");
//Variable for the value of the form and if condition met "then" do this if true "else" this if false
var response = inputs[0].value;
//Variables for creating a paragraph element and text per response
var node = document.createElement("p"),
textNode = document.createTextNode(response);
//Adding the response text to the paragraph and appending that to the bottom of the form
node.appendChild(textNode);
form.appendChild(node);
}
<form onsubmit="postComment(this); return false;">
<input type="text">
<p>
Comments Below:
</p>
</form>
以下是如何使用文本区域执行此操作,使用 Enter 和 Shift+Enter 标准:
document.addEventListener("DOMContentLoaded", function(event) {
var form= document.querySelector('form');
var textarea= document.querySelector('textarea');
textarea.onkeypress= function(e) {
if(e.which === 13 && !e.shiftKey) {
this.parentNode.onsubmit(e);
}
}
form.onsubmit= function(e) {
var textarea = form.querySelector('textarea');
var response = textarea.value;
var node = document.createElement('div');
node.innerHTML= response.replace(/\n/g,'<br>') + '<hr>';
form.appendChild(node);
textarea.value= '';
e.preventDefault();
}
});
textarea {
width: 50%;
height: 5em;
float: left;
}
p {
clear: both;
}
<form>
<textarea></textarea>
<input type="submit">
<p>
Comments Below:
</p>
</form>
关于javascript - 如何使用 HTML 和 Javascript 将元素添加到网页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27573375/