将事件侦听器添加到基于类的DOM元素 [英] Add event listener to DOM elements based on class

查看:154
本文介绍了将事件侦听器添加到基于类的DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,其中每个 tr td 只有类,我选择 td 具有我需要的类的元素

HTML:

 <表> 
< tr class =data>
< td class =cell> 1< / td>
< td class =cell2>< / td>
< / tr>
< tr class =data>
< td class =cell> 2< / td>
< td class =cell2>< / td>
< / tr>
< / table>

当mouseover td 加上 class =cell我必须在 td 之间获取我的鼠标和文字。这应该使用纯粹的JavaScript来完成,没有框架。我试过:

  var cell = document.querySelector('。cell'); 

function callback(){// do something}
cell.addEventListener('mouseover',callback(),false);

它不起作用,或者我犯了错误?

解决方案

  document.querySelector('。cell'); 

只会选择第一个具有 class ='cell'

为了将事件侦听器添加到所有这些元素,请使用 querySelectorAll()



它将返回一个NodeList(一种非活动DOM元素数组),其中 class ='cell'。您需要遍历它或使用索引访问一个元素。



例如:

  var cell = document.querySelectorAll('。cell'); 
for(var i = 0; i< cell.length; i ++){
cell [i] .addEventListener('mouseover',callback,false);

勾选小提琴


I have a table, where each tr and td have only classes, I have a problem with selection of td element having the class I need
HTML:

<table>
 <tr class="data">
  <td class="cell">1</td>
  <td class="cell2"></td>
 </tr>
 <tr class="data">
  <td class="cell">2</td>
  <td class="cell2"></td>
 </tr>
</table>

When mouseover td with class="cell" I have to get text between td on which my mouse and do something with this. This should be done with pure JavaScript, without frameworks. I tried:

var cell = document.querySelector('.cell');

function callback(){ //do something }
cell.addEventListener('mouseover',callback(),false);

It doesn't work, or maybe I did mistakes?

解决方案

document.querySelector('.cell');

Will only select the first element having class='cell'.

For adding event listener to all such elements, use querySelectorAll()

which will return a NodeList (a kind of array of inactive DOM elements) having class='cell'. You need to iterate over it or access one element using index.

For exapmle something like

var cell =document.querySelectorAll('.cell');
for(var i=0;i<cell.length;i++){
  cell[i].addEventListener('mouseover',callback,false);
}

check this fiddle

这篇关于将事件侦听器添加到基于类的DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆