2

我确定这已经被问过但我似乎无法在搜索中找到它我在由 php 生成的页面上有多个表单都带有 onCick 事件问题是它只会在任何其他点击之后拾取第一个事件从第一次单击产生相同的结果这是 javascript

   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++;
    }
?>
4

2 回答 2

2

Without knowing the inputs or seeing the result, it's hard to tell for sure, but it looks like you might be generating multiple instances of this form on the same page, giving you multiple page elements named "score_A" and "score_B". document.getElementById will then become a bit ambiguous.

Since you're already sending the form object, use that instead:

var scoreA = form.score_A.value;
...
于 2013-05-29T20:05:40.777 回答
1

您的代码基本上只有一个问题。您有多个相同 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" />

现在,你可以querySelector在你的 JS中写一个

function CompareScores(form) {
    var a = form.querySelector('.score_A').value;
    var b = form.querySelector('.score_B').value;
    //do something
}
于 2013-05-29T20:06:08.260 回答