如何使用javascript onBlur或onkeypress事件将行动态添加到表中



我有一个要求,我需要动态地向表中添加行。单击"尝试"按钮可以正常工作,但根据要求,我需要在单击屏幕上的任意位置时调用 Javascript 事件,所以我在模糊事件中使用了它,但它不起作用。

function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";

}
table, td {
border: 1px solid black;
}
<body onblur="myFunction()">
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>

</table>
<br>
<button onclick="myFunction()">Try it</button><br>
</body>

上面的代码片段适用于onclick功能,但是我想在单击屏幕上的任意位置或仅按键盘中的任何键时动态添加一行。

就像 Alex W. 说的那样,只需在正文上使用onClick(),但一定要在正文之前加载 JavaScript。

要检查您可以使用的按键

document.addEventListener('keydown', function(event) {
var key_code = event.keyCode;
if (key_code === 38) {
alert('test);
} 
}); 

最新更新