我在子页面上创建 div 时遇到问题。 我在子页面上有一个表单(ADD HERO),我想通过按下按钮在主页上创建一个 div。将表单中的数据保存到 localStorage,我使用 querySelection 检索元素,但不创建 div。这是我的代码:
主页:(Html)
<div class="heros"></div>
子页面(添加英雄):
<form method="POST" action="">
<input type="text" name="nameHero" placeholder="name" />
<input type="text" name="img" placeholder="foto>
<input type="text" name="price" placeholder="price / h" />
<textarea placeholder="desc Hero" name="descHero"></textarea>
<button id="btn-send" onclick="getValues(this.form)" >Submit</button>
脚本.js
let number = 1;
const btn = document.querySelector('#btn-send');
const heroClass = document.querySelector('.heros');
const newDiv = document.createElement('div');
function getValues(form) {
var nameValue = form.nameHero.value;
var imgValue = form.img.value;
var priceValue = form.price.value;
var descValue = form.descHero.value;
const obj = {
'nameHero': nameValue,
'img': imgValue,
'price': priceValue,
'descHero': descValue
};
localStorage.setItem(nameValue, JSON.stringify(obj));
newDiv.textContent = number;
heroClass.appendChild(newDiv);
}
在 div="heroes"我想添加新的 div。
最佳答案
您可以根据需要执行以下操作:
var div = document.createElement('div');
// optional
div.className = 'some-class-name';
div.id = 'an_Id';
div.innerHTML = '<span class="inner">Hello World!</span>';
div.textContent = 'Hello world.';
heroClass.body.appendChild(div);
关于javascript - 如何在另一个页面上创建一个div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54004941/