简体   繁体   English

不使用getAttribute('name')捕获第二个表单属性名称;

[英]Does not capture the second form attribute name with getAttribute('name');

I'm just looking at the JavaScript events for a project, but there is something I cannot find the reason why it does not work or does not show the event with getAttribute('name') when supposedly if there is the second like this: 我只是在查看一个项目的JavaScript事件,但是有一些原因我无法找到它为什么不起作用或无法通过getAttribute('name')显示该事件的原因,假设第二个事件是这样的:

<form name='otherRegistration'>
    <input type="email"></input> 
    <button class="btn btn-safe col-xs-6"></button>
</form>

<form name='registration'>
    <button class="btn btn-security col-xs-6"></button>
</form>

The question is that if it catches the name attribute of the first form name otherRegistration but does not capture the name of the second form registration which is weird and I don't have an idea why this happens, I have checked carefully and can not find the reason. 问题是,如果它捕获了第一个表单名称otherRegistration的name属性,但是没有捕获到第二个表单registration的名称,这很奇怪,而且我不知道为什么会这样,那么我已经仔细检查并找不到原因。

Once having the attribute name of the form does not enter the if which I do not understand because, if it revises with typeof and returns string 一旦具有表单的属性名称,就不要输入我不明白的if,因为如果它用typeof修改并返回字符串

I would appreciate if you help me understand why and what is the solution, here the code: 如果您能帮助我理解为什么以及什么是解决方案,请查看以下代码:

function userSessionSubmit() {

    var form = document.querySelector('form');
    var formName = '';

    form.addEventListener('click', function () {
        formName = form.getAttribute('name');

        console.log(formName);

        switch (formName) {
            case 'otherRegistration':
                alert('TRIGGER OTHER'); //works 
                break;
            case 'registration':
                alert('TRIGGER REGIS'); //does not work...
                break;
            default:
                alert('nothing');
                break;
        }
    });
};

userSessionSubmit();

document.querySelector(selector) selects one element - the first one found on the page. document.querySelector(selector)选择一个元素-在页面上找到的第一个元素。

To select multiple elements with one query you should use document.querySelectorAll(selector) and assign it to a variable. 要使用一个查询选择多个元素,应使用document.querySelectorAll(selector)并将其分配给变量。

Example code: 示例代码:

const forms = document.querySelectorAll('form'); // select all forms on the page
Array.prototype.forEach.call(forms, (form) => {
   form.addEventListener('click', listenerFunc); // add on click listener to every form
}); // iterate trough found elements

Edit: 编辑:

You should consider using unanonymous functions in your listeners - you can not use removeEventListener() on anonymous functions. 您应该考虑在侦听removeEventListener()使用匿名函数-不能在匿名函数上使用removeEventListener()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM