1

我有一个有 n 行的 html 表。每行都有一个名称和 2 个单选按钮。如果我单击一个单选按钮,我想显示一个说明票数的警报。我应该如何将单选按钮的名称传递给 Javascript,我应该如何进行计数?

这是PHP部分:

list($cols,) = $xlsx->dimension();
$var=0;
foreach( $xlsx->rows() as $k => $r) {
    $var++;
    echo '<tr>';
        echo '<td>'.$k.'</td>';
        echo '<td>'.( (isset($r[0])) ? $r[0] : '&nbsp;' ).'</td>';
        echo '<td><Input type = "Radio" Name ="vote'.$var.'" value= "pacada"  onclick = "AddPacada()"></td>';
        echo '<td><Input type = "Radio" Name ="vote'.$var.'" value= "toledo"  onclick = "AddToledo()"></td>';
    echo '</tr>';

这是Javascript部分:

function AddPacada(){
if(document.tally.pacada.checked == true){
    alert("You have clicked on Pacada.");
}
}function AddToledo(){
if(document.tally.toledo.checked == true){
    alert("You have clicked on Toledo.");
}
}
4

2 回答 2

1

您只需将其作为参数传递:

... onclick = "AddPacada(this)" ...
                         ^^^^

/* And in your function: */

function AddPacada(radio) {
    alert(radio.value);
}
于 2012-12-23T20:52:43.813 回答
0

onclick将您的 PHP 代码更改为onclick=tally(this)

然后这个 javascript 将提醒当前选择的总数:

<script>
  var selections = new Array(); //keep track of the selections
  function tally(e) {
    val  = e.value;
    name = e.name;

    selections[name] = val;  //an associative array or "hash"

    var totals = new Array();
    for (var key in selections) {
      var selection=selections[key];
      if(totals[selection] == undefined) { //set to 1 if not already initialized
        totals[selection] = 1;
      } else {
        totals[selection] += 1;
      }
    }
    alert(val + " has been selected " + totals[val] + " times");
  }

</script>

风格方面,我会尝试发出以下 HTML:

<input type="radio" name="var1" value="a" onclick="tally(this)"/>
<input type="radio" name="var1" value="b" onclick="tally(this)"/>

<input type="radio" name="var2" value="a" onclick="tally(this)"/>
<input type="radio" name="var2" value="b" onclick="tally(this)"/>

注意间距和大小写。

于 2012-12-23T21:25:18.130 回答