当我调用javascript函数时,html onkeypress的行为很奇怪,如何正确读取这里的输入



我们正在制作一个玩数独和解决数独的网站。为此,我们希望在按下数字时运行一个javascript函数。但按键通话的行为很奇怪。它确实给出了你要更改的单元格编号,但在按键时它看不到输入本身,除非你按两次。(?(或者输入。它如何正确地同时工作?也可以在这里找到:www.patternsinwords.com/sudoku,如果你想尝试的话。致以亲切的问候,Jaap


<html>
<head>
<script type="text/javascript">
function myFunction(val) {
var x = document.getElementById(val).value;
document.getElementById("alerts").innerHTML = "You changed " + x + " on cell " + (val+1);
}
</script>
<style> 
input[type=text] {
width: 20px;
border: none;
font-size: 20px;
align: center;
}
table{
border-collapse: collapse;
}
div{
align: center;
}
td:nth-child(3) {border-right: 2px solid black;}
td:nth-child(6) {border-right: 2px solid black;}
tr:nth-child(3) {border-bottom: 2px solid black;}
tr:nth-child(6) {border-bottom: 2px solid black;}
</style>
</head>
<body>
<center>
<?php
echo '<br><table border="3"><tr>';
$vertical = 0;
for ($i=0;$i<=80;$i++){
if ($i%9==0 && $i>0){
$vertical++;
echo '</tr><tr>';
}
echo '<td align="center" width="50" height="50"><input type="text" autocomplete="off" maxlength="1" id="'.$i.'" onkeypress="myFunction('.$i.')">';
}
echo '</tr></table>';
echo '<br><div id="alerts"></div>';
?>
</center>
</body>
</html>

由于事件顺序的原因,您无法从输入元素中获取新值。Keypress事件(最好使用keydown或input事件,因为Keypress是不推荐使用的事件(在值设置到input元素之前触发。使用按键事件,您只能获得先前设置的输入值。

要解决此问题,您可以使用"输入"事件:

echo '<td align="center" width="50" height="50"><input type="text" autocomplete="off" maxlength="1" id="'.$i.'" oninput="myFunction('.$i.')"></td>';

另一种方法是直接从事件中获取输入值。在我看来,这是最好的方法,因为您不必访问DOM来获得您已经拥有的值。如果你更喜欢使用基于事件的案例,你应该将你的功能更改为

function myFunction(e, cellId) {
var key = e.key;
document.getElementById("alerts").innerHTML = "You changed " + key + " on cell " + (cellId+1);
}

和的细胞标记

echo '<td align="center" width="50" height="50"><input type="text" autocomplete="off" maxlength="1" id="'.$i.'" onkdown="myFunction(event, '.$i.')"></td>';

相关内容

最新更新