我只是在看一个项目的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>
问题是,如果它捕获了第一个表单名称otherRegistration
的名称属性,但没有捕获第二个表单registration
的名称,这很奇怪,我不知道为什么会发生这种情况,我已经仔细检查过了,找不到原因。
一旦拥有表单的属性名,就不会输入if,这是因为,如果它修改为typeof并返回string
如果您能帮助我了解原因以及解决方案是什么,我将不胜感激,代码如下:
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();
发布于 2018-09-20 04:24:35
document.querySelector(selector)
选择一个元素-在页面上找到的第一个元素。
要通过一个查询选择多个元素,您应该使用document.querySelectorAll(selector)
并将其赋给一个变量。
示例代码:
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
编辑:
您应该考虑在侦听器中使用非匿名函数-您不能在匿名函数上使用removeEventListener()
。
https://stackoverflow.com/questions/52413662
复制相似问题