我正在尝试创建一个网页,其中用户在文本字段中键入一些文本,此文本如下所示。我设法通过在每次单击“提交”按钮时将此文本添加到数组中来显示用户键入的文本。每当有人加载网页时,无论是谁输入评论,我都希望用户在显示的“评论”中显示。所以它有点像留言簿。 到目前为止,我尝试做的是将数组保存在外部文件中,然后在页面重新加载时加载此文件。问题是我在stackoverflow和google中搜索时找不到办法。 您对我如何做到这一点有什么建议吗?
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="css/reset.css" type="text/css" rel="stylesheet">
<link href="css/style1.css" type="text/css" rel="stylesheet">
<title>Speak your mind</title>
</head>
<body>
<div id="header"><h1>Speak Your Mind</h1></div>
<div id ="description"><h2>Share with the world whatever is in your mind right now! </h2></div>
<div id="writeText"><textarea rows="4" cols="50" id="writeThought"></textarea></div>
<div id="submitThoughtContainer"><button id="submitYourThought">Submit Your Thought! </button></div>
<div id="thoughtsContainer"></div>
<script src="js/script.js"></script>
</body>
</html>
使用Javascript:
var thoughts = [];
window.addEventListener('load', function() {
var writeThought = document.getElementById('writeThought');
var recentThought;
var thoughtsContainer = document.getElementById('thoughtsContainer');
var submitYourThought = document.getElementById('submitYourThought');
var thoughtsTemporal = "";
submitYourThought.addEventListener('click', function() {
recentThought = writeThought.value;
thoughts.splice(0, 0, recentThought);
writeThought.value = "";
thoughtsTemporal = "";
for(var i = 0; i < thoughts.length; i++) {
thoughtsTemporal += '<div class="thoughts">'+ thoughts[i] +'</div>';
thoughtsContainer.innerHTML = "" + thoughtsTemporal;
}
});
});