Javascript动态表,每个单元格都有一个onmouse事件

Javascript Dynamic Table with each cell having an onmouse event?

本文关键字:有一个 onmouse 事件 单元格 动态 Javascript      更新时间:2023-09-26

我使用Javascript创建了一个动态表。现在我要做的是,对于每个动态生成的单元格,都有一个onmouseover事件,它将更改特定单元格的backgroundColor。

我遇到的问题是,当我生成表并尝试对每个动态生成的单元格使用onmouseover函数时,该函数只适用于最后生成的单元格。

这是我的代码副本。(注意:我只在Chrome上测试过这个)

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<style>
	table, th, td {
		border: 1px solid black;
		border-collapse: collapse;
		padding: 5px;
		text-align: center;
	}
</style>
<script type="text/javascript">
	var table;
	
	function init(){
		table = document.getElementById("mytable");
	}
	
	function makeCells(){
		init();
				
		for(var a=0;a<20;a++){
			var row = table.insertRow(-1);
			
			for(var b=0;b<20;b++){
				cell = row.insertCell(-1);
				cell.innerHTML = a*b;
				cell.onmouseover = function(){cell.style.backgroundColor = "yellow";};
			}
		}
	}
</script>
</head>
<body onload="javascript: makeCells();">
	<table id="mytable"></table>
</body>
</html>

如有任何建议,我们将不胜感激。

一些改进。我要改变的3件事:

  1. 不要使用javascript编辑内联样式。而是添加或删除一个类。参见#3。

  2. 不要在"onload"、"onmouseover"中做太多事件处理程序。最好添加一个事件侦听器。

  3. 一次性添加所有新元素比单独添加要好。请参阅本文:https://developers.google.com/speed/articles/reflow

这里有一种优化Javascript的方法:

HTML

<table id="table"></table>

CSS

body {
  padding: 40px;
}
.yellow {
  background: yellow;
}
td {
    padding: 10px 20px;
    outline: 1px solid black;
}

JavaScript

    function propegateTable() {
      var table = document.getElementById("table");
      //will append rows to this fragment
      var fragment = document.createDocumentFragment();
      for(var a=0; a<10; a++){ //rows
          //will append cells to this row
          var row = document.createElement("tr");
          for(var b=0;b<5;b++){ //collumns
            var cell = document.createElement("td");
            cell.textContent = a + ", " + b;
            // event listener
            cell.addEventListener("mouseover", turnYellow);
            row.appendChild(cell);
          }
          fragment.appendChild(row);
        }
      //everything added to table at one time
      table.appendChild(fragment);
    }
    function turnYellow(){
      this.classList.add("yellow");
    }
    propegateTable();

http://codepen.io/ScavaJripter/pen/c3f2484c0268856d3c371c757535d1c3

实际上,我自己在代码中找到了答案。

行中:

cell.onmouseover = function(){cell.style.backgroundColor = "yellow";};

我把它改成:

cell.onmouseover = function(){this.style.backgroundColor = "yellow";};
相关文章: