观察表格提交

时间:2016-08-27 10:09:08

标签: javascript events javascript-events ecmascript-6 event-delegation

在我的应用程序中,我需要通过JavaScript提交表单。我知道我可以用这段代码做到这一点:

[...document.querySelectorAll('form')].forEach(form => {
    form.addEventListener('submit', e => {
        //doing the processing here
        e.preventDefault();
    })
})

从服务器我获得完全生成的HTML表单,我会在必要时将其注入DOM(或从那里删除它们)。通过这样做,已注册的事件处理程序停止工作,因为表单元素已删除或未注册。

是否可以注册全局»提交听众«,与之相当:

window.addEventListener('click' e => { … });

如果DOM发生变化,永远不会被删除的内容,或者每次DOM更改时我是否必须注册提交处理程序?

不是一个公开的,因为所提到的授权策略是我正在寻找的,但不是针对点击事件,而是针对提交事件。

1 个答案:

答案 0 :(得分:1)

You can definitely catch submit events as they bubble up, so what you want can be achieved by listening from a parent element that is always present as the dynamic forms are added and removed. I like doing this thing with a wrapper element with an ID, as opposed to listening a the body or html level. Here's a very simple example using just vanilla js. Codepen here: http://codepen.io/bsidelinger912/pen/RGbWYb

HTML:

<div id="form-wrapper">
  <h2>Form 1</h2>
  <form id="form1">
    <input name="test" placeholder="enter something" />
    <input type="submit" value="submit" />
  </form>

  <h2>Form 2</h2>
  <form id="form2">
    <input name="test" placeholder="enter something" />
    <input type="submit" value="submit" />
  </form>
</div>
<button id="form-adder">
  + Add a form
</button>

Javascript

var formWrapper = document.getElementById('form-wrapper');

// capture the submit event in the parent div
formWrapper.addEventListener("submit", function(e) {
  e.preventDefault();
  console.log('submit captured');

  var thisForm = e.srcElement || e.originalTarget;
  console.log('form id:' + thisForm.id);
  console.log(thisForm.test.value);
});

// dynamically add divs and see we can still capture the submit
var divNum = 3;
function addDiv(e) {
  e.preventDefault();

  formWrapper.innerHTML += '<h2>Form ' + divNum + '</h2>\
  <form id="form' + divNum + '">\
    <input name="test" placeholder="enter something" />\
    <input type="submit" value="submit" />\
  </form>';

  divNum++;
}

document.getElementById('form-adder').addEventListener('click', addDiv);