创建多个onmouseover事件时,它们会“覆盖”先前的事件,直到代码仅识别出最后一个事件为止。

问题描述 投票:0回答:1
因此,我试图创建一个表,如果鼠标悬停在表中的某个单元格上,背景颜色将发生变化。桌子很大(8 x 19),所以我正在动态创建它。这是我的整体代码

<html> <meta charset="UTF-8"> <body> Test <table id="scheduling"></table> </body> <style> body { color: red; } table, th, tr { border: 2px solid black; width: 10vw; } </style> <!--<link rel="stylesheet" type="text/css" href="scheduler.css">--> <script> function createSchedulingTable() { var scheduling = document.getElementById("scheduling"); var firstrow = document.createElement('tr'); var categories = ['Times', 'S', 'M', 'T', 'W', 'R', 'F', 'Sa']; for (var a = 0; a < 8; a++) { var th = document.createElement('th'); th.innerHTML = categories[a]; firstrow.appendChild(th); } scheduling.appendChild(firstrow); for (var a = 0; a < 18; a++) { var therow = document.createElement('tr'); therow.innerHTML = (a + 7) + ':00'; if (a + 7 == 24) { therow.innerHTML = '0:00'; } for (var b = 0; b < 7; b++) { var th = document.createElement('th'); th.id = ' cell' + a + ',' + b; th.onmouseenter = function() { highlight(th); }; th.onmouseout = function() { dehighlight(th); }; th.innerHTML = 'cell'; therow.appendChild(th); } scheduling.appendChild(therow); } } createSchedulingTable(); function highlight(element) { //alert('highlighting ' + this.id); element.style.background = 'yellow'; } function dehighlight(element) { //alert('highlighting ' + this.id); element.style.background = 'white'; } </script> </html>
一切对我来说都很好。但是,当我对其进行测试时,只有最后一个表格单元(右下角)会更改其背景颜色。我将鼠标放在任何单元格中,只有最后一个单元格会发黄光。就像代码正在删除上一个元素的上一个onmouseenter并将其替换为新元素一样。为什么会这样?

因此,我试图创建一个表,如果鼠标悬停在表中的某个单元格上,背景颜色将发生变化。桌子很大(8 x 19),所以我正在动态创建它。这是我的整体...

javascript html css
1个回答
1
投票
[onmouseover是一种方法,当您再次定义它时将被覆盖。
© www.soinside.com 2019 - 2024. All rights reserved.