输出的javascript版本可以插入到Div的代码中吗?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (85)

我有一个表单,当用户点击添加或减去用户按钮时,添加和减去较小的表单,我想要做的是每次用户点击div标签内的ID标签的添加按钮时添加+1 :

<div id="formwrap" class="test" name="test">im a form in this formwrap</div>

现在说用户单击一个添加按钮,一个新表单将弹出当前表单下方并使用javascript的打印或回显版本,这将是使用.append(html)或者某些东西为div创建的新代码这个:

<div id="formwrap" class="test" name="test">im a form in this formwrap</div>
<div id="formwrap" class="test2" name="test2">im a form in this formwrap</div>

如果有人在哪里点击添加按钮,2会变为3

<div id="formwrap" class="test(+1 code would go here)" name="test(+1 code would go here)">im a form in this formwrap</div>
提问于
用户回答回答于
var count = 0
var formwrap = document.getElementById('formwrap');
formwrap.dataset.name = "aName" + count
// increment count on click
用户回答回答于

//Create a private counter var
const counter = (function() {
  var formCount = 0;
  return {
    value: () => formCount,
    increment: () => ++formCount
  }
})();

//A function that will generate a "form" element
const ID_PREFIX = 'formwrap_';
const generateFormEl = () => {
  let el = document.createElement('div');
  el.setAttribute('id', `${ID_PREFIX}${counter.increment()}`);
  el.setAttribute('class', 'test');
  el.setAttribute('name', 'test');
  el.appendChild(document.createTextNode(`ID: ${el.getAttribute('id')}`));
  return el;
};

//Store your DOM elements in some vars
const forms = document.querySelector('#forms');
const btn = document.querySelector('[type="button"]');

//Add a form element to the DOM on click
btn.addEventListener('click', () => {
  const form = generateFormEl();
  forms.appendChild(form);
});
<div id="container">
  <input type="button" value="Add a form" />
  <div id="forms"></div>
</div>

扫码关注云+社区

领取腾讯云代金券