实现代码
// 部分基于HTML form元素的表单提交方法,将form节点克隆出来然后进行数据修改调整后重发
// 注意:cloneNode不会复制select的值,因此需要手工遍历源form节点然后复制一个带有value的select/input (https://github.com/whatwg/dom/issues/644)
function formDataModifier(formNode, modifyFn) {
var clonedForm = formNode.cloneNode(true);
var attachedNode = document.body.appendChild(clonedForm);
// clone all select fields
var allOldSelects = formNode.querySelectorAll("select");
for (var i = 0; i < allOldSelects.length; i++) {
if (allOldSelects[i].name) {
var node = attachedNode.querySelector('select[name=' + allOldSelects[i].name + ']');
if (node) node.value = allOldSelects[i].value;
}
}
modifyFn && modifyFn(attachedNode);
attachedNode.addEventListener('submit', function(e) {
// console.log(e);
setTimeout(function() {
if (attachedNode) document.body.removeChild(attachedNode);
clonedForm = null; // destroy
}, 100);
})
return attachedNode;
}
而对于已经插入的节点元素,不能使用form.submit()
触发,需要手工改为:
if(document.createEvent) {
form.dispatchEvent(new Event('submit'));
} else {
// IE
var event = document.createEventObject();
form.fireEvent("onsubmit", event);
}