更改变量值时出现`alert`错误

时间:2017-01-04 02:00:10

标签: javascript html

我有单选按钮,可根据选择的数字来提醒不同的数字。



var radioButtons = document.querySelectorAll('input[type=radio]');

var chanceoflive1 = 0;
var user;
function choose(choice){
    user = choice;
}

function changechanceoflive1(){
    if (user == 'bricks') {
        chanceoflive1 = 1;
    }
    else if (user == 'wood') {
        chanceoflive1 =3
    }
    else if (user == 'stone') {
        chanceoflive1 = 2
    }
    alert(chanceoflive1);
}

<div id="radiobuttons" class="container" name="buttons" align=center>

  <h2>I Want my Building to be Made of:</h2>

  <ul>
  <li>
    <input type="radio" id="brick-option" name="material" value="1" onClick="choose('bricks')" checked="checked">
    <label for="brick-option">Bricks</label>

    <div class="check"></div>
  </li>

  <li>
    <input type="radio" id="wood-option" name="material" value="3" onClick="choose('wood')">
    <label for="wood-option">Wood</label>

    <div class="check">
      <div class="inside"></div>
    </div>
  </li>

  <li>
    <input type="radio" id="stone-option" name="material" value="2" onClick="choose('stone')">
    <label for="stone-option">Stone</label>

    <div class="check">
      <div class="inside"></div>
    </div>
  </li>
  </ul>
</div>

<form action="chooseheight.html">
  <div class="wrapper">
    <button class="button" onClick="changechanceoflive1()" align=center>Submit</button>
  </div>
</form>
&#13;
&#13;
&#13;

当我点击木头时,它会发出警告3,这是完美的。当我点击石头时,它会提醒2,这很棒。虽然,当我点击砖块时,它会提示0.为什么?

2 个答案:

答案 0 :(得分:1)

将第2行更改为 var chanceoflive1 = 1; 一切都会按预期工作。初始单选按钮已预先选定。没有点击砖块然后回到砖块,chanceoflive1仍然是其初始值0。

答案 1 :(得分:0)

这是因为如果用户没有点击任何复选框,用户就无法选择任何内容。由于您希望将砖块作为默认选项,因此您可以在脚本末尾调用choose('bricks'),或者只在变量声明中设置var user = 'bricks';