在页面上显示用户输入

我被这个问题困扰了一段时间,但我无法完全弄清楚。我想将用户输入显示为 h1 元素。我该怎么做呢?


let allAssignments;


if (localStorage.getItem("everyAssignment")) {

  allAssignments = JSON.parse(localStorage.getItem("everyAssignment"))

} else {

  allAssignments = []

}


function submitFunc() {

  let names = document.getElementById("name").value;

  allAssignments.push(names)

  localStorage.setItem("everyAssignment", JSON.stringify(allAssignments));

  let finalArray = JSON.parse(localStorage.getItem("everyAssignment"));

}

<button onclick="submitFunc()">Submit</button>

<input placeholder="Enter Name Here" id="name">

我想为本地存储中的每个项目创建一个 div 元素,并使用 .innerHTML 插入一个 h1 元素,其中包含数组中每个值的名称。我该怎么做呢?



元芳怎么了
浏览 99回答 2
2回答

慕桂英4014372

你可以这样做:const submitFunc = () => {&nbsp; const value = document.getElementById('name').value;&nbsp; const parent = document.createElement('div');&nbsp; const pTag = document.createElement('p');&nbsp; pTag.innerText = value;&nbsp; parent.appendChild(pTag);&nbsp; document.body.appendChild(parent);}<button onclick="submitFunc()">Submit</button><input placeholder="Enter Name Here" id="name">

猛跑小猪

如果你想将其显示为 H1 元素,你可以执行以下操作&nbsp; &nbsp; const submitFunc = () => {&nbsp; &nbsp; &nbsp; const value = document.getElementById('name').value;&nbsp; &nbsp; &nbsp; const parent = document.createElement('div');&nbsp; &nbsp; &nbsp; const hTag = document.createElement('h1');&nbsp; &nbsp; &nbsp; var node = document.createTextNode(value);&nbsp; &nbsp; &nbsp; hTag.appendChild(node);&nbsp; &nbsp; &nbsp; parent.appendChild(pTag);&nbsp; &nbsp; &nbsp; document.body.appendChild(parent);&nbsp; &nbsp; }这是要使用的标记。<button onclick="submitFunc()">Submit</button><input placeholder="Enter Name Here" id="name">
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5