将3个事件侦听器添加到表的每一行 [英] Add 3 event listeners to every row of a table

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

问题描述

首先,我创建一个容器来存储所有行。这是一个数组。然后,我遍历此数组的每个元素,并想向它们添加带有事件和功能的事件侦听器-但它不起作用。后来我也添加了功能。作为检查,我将所有行都涂成了粉红色。因此,循环开始运行,并且存在行数组。

First I create a container to store all rows. It's an array. Then I loop through every element of this array, and I would like to add event listener with event and function to them - but it does not work. Later I add the functions too. As a check I painted all rows pink.. and that worked. So the loop runs and the array of rows exists.

 <script>
    var rows = document.getElementsByTagName("tr");
    for (i=0; i < rows.length; i++) {
        rows[i].addEventListener("onmouseover", mouseOver);
        rows[i].addEventListener("onmouseout", mouseOut);
        rows[i].addEventListener("click", mouseClick);
        rows[i].style.color="pink";  //testing the loop and the array - works
    }       
    function mouseOver() {
        document.getElementByTagNameId("tr").style.color = "red";
    }    
    function mouseOut() {
        document.getElementByTagNameId("tr").style.color = "black";
    }    
    function mouseClick(){  
       // nothing here yet
    }
    </script>


推荐答案

我使用了错误的事件名称。不能使用 on前缀。不喜欢:onmouseover。而是鼠标悬停事件。

I used the wrong event name. No "on" prefix can be used. Like no: onmouseover. Instead: mouseover event.

<script>
var rows = document.getElementsByTagName("tr");
alert(rows.length); 
for (i=1; i < rows.length; i++) {
    rows[i].addEventListener("mouseover", mouseOver);
    rows[i].addEventListener("mouseout", mouseOut);
    rows[i].addEventListener("click", mouseClick);
    rows[i].style.color="pink";

}   

function mouseOver() {
    this.style.color = "red";
}

function mouseOut() {
    this.style.color = "black";
}

function mouseClick(){
    alert("Row was clicked!");
}
</script>

这篇关于将3个事件侦听器添加到表的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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