单击按钮后,如何将文本区域值保存在列表中



我正试图为我的日志项目添加一个保存功能,该项目只是一个静态网站。

基本上有三个部分。

  1. 文本区域
  2. "保存"按钮
  3. 潜水储存日志

我想要实现的是,如果我单击保存按钮,它将把条目保存在项目符号列表中。。。如果我再次点击保存按钮,它会在下面创建另一个条目,以此类推

以上只是一个开始。。在那之后,我计划能够将该列表值保存在本地存储中,所以下次打开该工具时,该列表应该仍然存在,并且我应该能够向其添加更多内容。

如果我能在每个日志之前添加时间戳(日期和时间(,还有另一个好处。例如:

  • 2022年11月3日上午5:00-请注意
  • 2022年3月15日上午9:32-请注意
  • 2022年3月24日上午7:15-请注意

我该如何构建它?现在我只需要显示HTML和CSS。。但我希望有人能向我展示如何做到这一点。请参阅下面的代码:

<textarea id="textarea3" cols="50" rows="10"></textarea>
<button id="save-btn">Save textarea</button>
<div id="logs">
<ul>
<li></li>
</ul>    
</div>

很抱歉有这么多问题。。。但是提前感谢您的帮助!

这是您尝试做的事情的一个非常基本的实现。本质上,您需要采取以下步骤:

  • 在加载HTML时,使用其ID将onclick事件侦听器附加到保存按钮。请参阅DOMContentLoaded事件
  • 单击该按钮时,使用其ID和value属性从<textarea>获取文本
  • 使用列表ID获取列表,并创建新的列表项<li>
  • 将文本区域中的文本分配给列表项
  • 使用toLocaleString()获取时间戳

/**
* This function handles the onclick event meaning it will be called whenever the button is clicked.
*/
function onSave() {
// get textarea element
const textArea = document.getElementById("textarea3");
// retrieve the value within it
const note = textArea.value;
// add the note to the list
addNote(note);
}
/**
* This function adds a new note to the list of notes with a timestamp.
* @param {string} noteText text to be added to list
*/
function addNote(noteText) {
// get the list
const logList = document.getElementById("log-list");
// create a new list item
const listItem = document.createElement("li");
// now set the text for this list item using a timestamp and the text provided as parameter
listItem.textContent = `${new Date().toLocaleString("en-US")}  -  ${noteText}`;
// at this stage the list element is not yet added to the list, so add it at the bottom of the list now
logList.appendChild(listItem);
}
// wait until all the HTML has been loaded!
window.addEventListener('DOMContentLoaded', (event) => {
// get the button element
const saveBtn = document.getElementById("save-btn");
// attach an event listener for the "click" event. Every time the button i clicked onSave() should be called
saveBtn.addEventListener("click", onSave)
});
<textarea id="textarea3" cols="50" rows="10"></textarea>
<button id="save-btn">Save textarea</button>
<div id="logs">
<ul id="log-list">
</ul>
</div>

最新更新