2017-08-29 53 views
0

我必须编写一个代码,它可以在没有循环和jquery的情况下在所有具有相同类的输入上运行click事件。在没有循环和jQuery的情况下在所有具有相同类的元素上添加Click事件

我想出是:

document.body.addEventListener('click', function (click) { 
    if (click.target.className == 'abc') { 
     document.frame.screen.value += this.value; 
    } 
}); 

,并单击作品,但我得到了undefined的而不是点击输入包含值。

+0

'this'将是'document.body'所以'value'将不存在。 – evolutionxbox

回答

0

并点击工程,但我得到了未定义,而不是点击输入包含的值。

因为您在获取值时使用了this而不是click.target;你想使用click.target

document.frame.screen.value += click.target.value; 
// Here -----------------------^^^^^^^^^^^^ 

this在你的处理器将是document.body。您在检查课程时已正确使用click.target,但在获取该值时未使用click.target

一些注意事项:

  • FWIW,在事件处理程序的事件参数的名称通常是evente,不click
  • 元素可以有多个类,这些类都将在className中。 如果这对您来说可能是个问题,您可以改为.classList.contains("abc")。 (classList可用于所有现代浏览器,并且可以将其填充到过时的元素上。)
  • 对于input元素来说这不是问题,但将来如果要使用可具有后代元素的元素执行此操作,需要有一个循环处理的可能性点击的是你的目标元素的后代:

    var node = event.target; 
    while (!node.classList.contains("abc")) { 
        if (node === this) { 
         return; // The click didn't pass through a matching element 
        } 
        node = node.parentNode; 
    } 
    // Use it here 
    
+0

非常感谢!我是一个JavaScript的蹒跚学步,并不完全理解DOM :) –

相关问题