问题
I'm trying to add a comments from user, so I just tried to read the input and send it to print it , but the problem is that the printed input disappears as soon as I refresh the page or enter another input.
so I want to keep all user's appearing always even when refreshing the page or re-entering a new comment.
code :
<div>
<input type="text" name="comments" placeholder = "Your comment goes here .. " class = "sug-box" id = "UserComment">
<button class = "send-box" onclick="go()">Add</button><i class="fa fa-send-o"></i>
<p id = "t"></p>
</div>
<script>
function go(){
var x = document.getElementById("UserComment").value;
document.getElementById("t").innerHTML = x;
}
</script>
回答1:
I think I have a solution that should work for you. I have renamed and refactored some of your code a little, feel free to change it back to the original version if you wish. For me, this was easier to read. I also put the JS in a separate file, but you could accomplish the same task using the script tag.
Here is a link to a JSFiddle that shows it in action JSFiddle User-Comments-App. The code in the fiddle has been modified to work on that site, don't pay attention to it, look at the example below! You can't do page refreshes on JSFiddle so I simulated it with a Refresh Page button and a little timer function that clears the list then repopulates it from local storage.
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<!-- calls this function on refresh to pull any coments from local storage -->
<body onload="populateUL()">
<div>
<input type="text" name="comments" placeholder = "Your comment goes here .. " class = "sug-box" id = "UserComment">
<button class = "send-box" onclick="parseUserComment()">Add</button><i class="fa fa-send-o"></i>
<p id = "t"></p>
</div>
<div id="comment-container">
<ul>
<!-- <li> items will be inserted here -->
</ul>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
JavaScript
var commentUL = document.getElementById('comment-container').firstElementChild;
var commentNumber = 0;
function parseUserComment() {
var userComment = document.getElementById("UserComment").value;
storeUserComment(userComment, commentNumber);
displayUserComment(userComment);
commentNumber++;
}
function displayUserComment(userComment) {
var li = document.createElement('li');
li.textContent = userComment;
commentUL.appendChild(li);
}
function storeUserComment(userComment, commentNumber) {
window.localStorage.setItem(`comment-${commentNumber}`, userComment);
}
function populateUL() {
if (window.localStorage.length > 0) {
var i;
for (i = 0; i < localStorage.length; i++) {
var userComment = window.localStorage.getItem(`comment-${i}`);
displayUserComment(userComment);
}
// we need to reset the counter to begin in the last element of the array when we refresh the page.
commentNumber = localStorage.length;
}
}
Here's a brief breakdown of what's going on, let me know if you have any questions or if something is unclear.
Code Explanation
When the user clicks the 'Add' button, the parseUserComment() function will run. This function takes care of storing the comment in local storage, and displaying the comment on the screen. You'll notice that we pass the work of displaying the comment and storing the comment on to helper functions storeUserComment() and displayUserComment(). The only thing that parseUserComment() actually does is get the user's comment and increment the counter commentNumber:
var commentNumber = 0;
function parseUserComment() {
var userComment = document.getElementById("UserComment").value;
storeUserComment(userComment, commentNumber);
displayUserComment(userComment);
commentNumber++;
}
So, we have the user's comment, and we pass along the userComment to the helper function storeUserComment, which is just a single function call that add's the comment to local storage, using a naming convention 'comment-{commentNumber}'. This would mean the first comment would be 'comment-0', the second 'comment-1'. We use the 0-based system like in arrays. Note the use of template literals to allow us to easily concatenate the commentNumber to the string:
function storeUserComment(userComment, commentNumber) {
window.localStorage.setItem(`comment-${commentNumber}`, userComment);
}
After we have stored the user comment, we want to display it. And this function will also be used to display the user comments on a page refresh. We simply create a new 'li' element, and then make that elements text content the userComment. We then add this element to the 'ul' that sit's inside the div.comment-container, which we selected at the beginning of the file, using the appendChild() method:
// at beginning of file
var commentUL = document.getElementById('comment-container').firstElementChild;
function displayUserComment(userComment) {
var li = document.createElement('li');
li.textContent = userComment;
commentUL.appendChild(li);
}
So that covers the parseUserComment() function and the helpers it calls. Next we need to see how to show the user's comments when the page refreshes. For this, we add an event listener to the 'body' element for the 'onload' event:
<body onload="populateUL()">
The populateUL() function will check to see if there are any items in local storage, and if so, it will loop through those items and call the displayUserComment() function for each item:
function populateUL() {
if (window.localStorage.length > 0) {
var i;
for (i = 0; i < localStorage.length; i++) {
var userComment = window.localStorage.getItem(`comment-${i}`);
displayUserComment(userComment);
}
// bottom of function left off for clarity
At the end of the function, we have to be sure to set the commentNumber to the length of the localStorage array, which would be the last element. So, if you had two comments in localStorage, you would have 'comment-0' and 'comment-1'. The length of localStorage would be 2. We would print out 'comment-0' and 'comment-1' in the loop, then the 'i' variable would increment to 2, and the loop would stop. At this point, we can assign the length of localStorage to the commentNumber, so that if the user wanted to add a new comment, it would start numbering at 2 ('comment-2'):
commentNumber = localStorage.length;
回答2:
There are two ways to do this depending on what your use case is.
The first is to use localstorage, which is significantly easier than using a database but has some downsides. Localstorage could be used if the comments were personal (meaning nobody else sees them). The problem with this is that localstorage is insecure.
Localstorage is a set key/value pairs stored on the users machine until deleted.
This is how you use localstorage:
// Place something in localstorage:
window.localStorage.setItem('key', 'value')
//Get something from localstorage:
window.localStorage.getItem('key')
//Delete item from localstorage
window.localstorage.removeItem('key')
Your full application might look something like this:
Javascript:
document.getElementById('comment').innerHTML = window.localStorage.getItem('comment') || ''
HTML:
<!DOCTYPE html>
<html>
<head>
<title>*title here*</title>
</head>
<body>
<textarea placeholder="Type comment here" id="comment"></textarea>
<br/>
<button onmouseup="window.localStorage.setItem('comment',document.getElementById('comment').value)">Submit</button>
</body>
</html>
The second way to do this is to use a database.
There are many different ways to do this, but I would recommend using node.js + express for middleware and mongodb for your database.
Here are some links to get you started:
node.js
npm
express
mongodb
Let me know if I missed anything and/or misunderstood the question.
来源:https://stackoverflow.com/questions/57547302/how-to-keep-users-input-printed