javascript - 如何在另一个页面上创建一个div?

标签 javascript html

我在子页面上创建 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/

相关文章:

javascript - dom-repeat with `<span>` 空白解决方案

jquery - IE 问题集中在使用 JQuery 的选择元素中动态添加的选项

javascript - 如何实现响应式设计,在缩放时保持按钮和其他东西相对于背景图像的位置?

javascript - 如何在通过模板文字创建的元素中添加事件监听器?

javascript - 如何在javaScript中刷新页面后更新数据库中表的星级?

javascript - 可动态 - 每次页码更改时,记录都会附加到先前的列表中

html - Http 304 和缓存控制 : no-cache

jquery - Bootstrap 内联表单字段不对齐顶部和底部

html - 高度 100% 的 Fieldset child 太大了

javascript - 在 jQuery + Datatables 中设置 `processData: false` 会将未知内容附加到我的 Ajax 调用的 URL