Javascript 多个表单onclick事件仅适用于第一个表单
我肯定以前有人问过这个问题,但我在搜索中似乎找不到 我在php生成的页面上有多个表单,所有表单都带有onick事件 问题是,它只会在任何其他单击都会从第一次单击产生相同结果之后拾取第一个事件 这里是javascriptJavascript 多个表单onclick事件仅适用于第一个表单,javascript,Javascript,我肯定以前有人问过这个问题,但我在搜索中似乎找不到 我在php生成的页面上有多个表单,所有表单都带有onick事件 问题是,它只会在任何其他单击都会从第一次单击产生相同结果之后拾取第一个事件 这里是javascript function CompareScores(form) { var scoreA = document.getElementById("score_A").value; var scoreB = document.getElementById("score_B"
function CompareScores(form)
{
var scoreA = document.getElementById("score_A").value;
var scoreB = document.getElementById("score_B").value;
if(scoreA > scoreB){
alert('Score A is Larger ' + scoreA)
}else{
alert('Score B is Larger ' + scoreB)
}
}
以及php生成表单
<?php
while($i<=$numPrelimTeams) {
if($i!=$e) {
?>
<form action="processScores.php" method="post"><p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_A" name="score_A" size="1"></u></p>
<input type="hidden" name="team_A" value="<?php echo $prelimTeam[$i]; ?>">
<input type="hidden" name="game" value="<?php echo $game_num; ?>">
<p class="right">Game # <?php echo $game_num; ?> ) <input type="button" value="Enter Scores" onClick="CompareScores(this.form)"></p>
<?php
}else{
?>
<p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_B" name="score_B" size="1"></u></p>
<input type="hidden" name="team_B" value="<?php echo $prelimTeam[$i]; ?>">
</form><br><br><br>
<?php
$game_num++;
$e=$e+2;
}
$i++;
}
?>
-->分数:
在不知道输入或不看到结果的情况下,很难确定,但看起来您可能在同一页面上生成了此表单的多个实例,为您提供了多个名为“score_A”和“score_B”的页面元素。document.getElementById将变得有点模棱两可
由于您已经发送表单对象,请改用它:
var scoreA = form.score_A.value;
...
您的代码基本上只有一个问题。您有多个相同ID的实例
要修复它,请尝试类似的方法
<input type="text" class="small score_A" name="score_A" size="1" />
<input type="text" class="small score_B" name="score_B" size="1" />
function CompareScores(form) {
var a = form.querySelector('.score_A').value;
var b = form.querySelector('.score_B').value;
//do something
}