我有一个输入字段,可以在其中输入数据。
数据进入表并创建一个新行,其中包含数据。
最新行始终位于顶部。
我希望表格仅显示最新行并隐藏所有其余行(意味着仅显示一行), 当我使用事件侦听器将鼠标悬停在它上面时,我希望它展开并显示隐藏的所有其他行。 当我鼠标移出时,我希望表格再次折叠并仅显示最新行,同时隐藏所有其余行。
我该怎么做? 每次我尝试解决这个问题时,我都会让事情变得更糟 现在由于某种原因我根本没有显示新行。
提前致谢!
这就是我的代码:
HTML:
<body>
<div class="container">
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<form>
<label for="fName">Name</label><br />
<input type="text" id="fName" name="fName" /><br />
<input type="submit" id="submitBtn" />
</form>
</div>
CSS:
table {
color: black;
width: 200px;
border-collapse: collapse;
left: 100px;
z-index: 1;
position: absolute;
box-shadow: 0px 2px 5px black;
}
.expand{
display: table-row !important;
}
.collapse{
display: none;
}
tr:not(:first-child){
display: none;
}
JS:
"use strict";
let inputBox = document.querySelector("#fName");
let tBody = document.querySelector("tbody");
const table = document.querySelector('table');
function addRow() {
let row = tBody.insertRow(0);
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
cell1.innerHTML = inputBox.value;
cell2.innerHTML = "text2";
inputBox.value = " ";
row.classList.add('tr');
}
tBody.classList.add('collapse');
document.querySelector("#submitBtn").addEventListener("click", function (event) {
event.preventDefault();
addRow();
});
// collapst/expand event listeners:
table.addEventListener('mouseover', function(){
tBody.classList.remove('collapse');
tBody.classList.add('expand');
})
table.addEventListener('mouseout', function(){
tBody.classList.remove('expand');
tBody.classList.add('collapse');
})
看来您的实施需要一些调整。在 addRow() 函数中,确保新添加的行被显示,而其他行被隐藏。
function addRow() {
let row = tBody.insertRow(0);
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
cell1.innerHTML = inputBox.value;
cell2.innerHTML = "text2";
inputBox.value = " ";
row.classList.add('tr');
/* here */
tBody.classList.remove('expand');
tBody.classList.add('collapse');
还在 css 文件中修改展开和折叠类,如下所示:
/* This will hide all rows except the first one */
.collapse tr:not(:first-child) {
display: none;
}
/* This class will show all rows */
.expand tr {
display: table-row;
}