stopPropagation()on submit not working

时间:2017-05-07 21:23:09

标签: javascript event-handling event-listener

我在停止在表单中传播提交时遇到问题。似乎无论我在网页中点击哪一个事件都被触发 - 如何将其修复为仅在单击提交按钮时触发?

document.addEventListener('DOMContentLoaded', bindButtons);

function bindButtons() {
    var buttons = document.getElementsByTagName('submit');

    Array.prototype.forEach.call(buttons, addEventListener('click', function(event) {
        var req = new XMLHttpRequest();
        req.open("GET", url, true);

        req.addEventListener('load', function(event) {
             // do stuff
        })

        event.preventDefault();
        event.stopPropagation();

        req.send(null);    
    }))
}

1 个答案:

答案 0 :(得分:1)

提交不是有效标记,您可以使用以下代码找到提交按钮:

var submitButtons = document.getElementByTagNames('button').filter(button => button.getAttribute('type') === 'submit');

或者,更详细:

var submitButtons = document.getElementByTagNames('button').filter(function(button){ 
    return (button.getAttribute('type') === 'submit')
);