使用单选按钮更改变量值

时间:2016-12-21 22:40:22

标签: javascript html5

我希望变量(chanceoflive)与localStorage存储。然后,我有单选按钮。我想要它,以便根据选择的单选按钮,变量chanceoflive将被更改。这就是我所拥有的:



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

function changechanceoflive(){
    if (user == brick) {
        chanceoflive += 1;
    }
    else if (user == wood) {
        chanceoflive +=3
    }
    else if (user == stone) {
        chanceoflive +=2
    }
    localStorage.setItem("chanceoflive", chanceoflive);
}

function test(click){
    alert(chanceoflive);
}

<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')">
      <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="test();changechanceoflive()" align=center>Submit</button>
  </div>
</form>
&#13;
&#13;
&#13;

虽然,它总是只发出警报0.是否存在localStorage或其他问题?

2 个答案:

答案 0 :(得分:1)

我修复了你的代码:

<ul>
<li>
  <input type="radio" id="brick-option" name="material" value="1" onClick="choose('bricks')">
  <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>

JS

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

function changechanceoflive(){
    if (user == 'bricks') {
        chanceoflive += 1;
    }
    else if (user == 'wood') {
        chanceoflive +=3
    }
    else if (user == 'stone') {
        chanceoflive += 2
    }
    localStorage.setItem("chanceoflive", chanceoflive);
}

function test(click){
    alert(chanceoflive);
    alert(localStorage.chanceoflive);
}

但是使用您的代码,如果用户重新加载页面然后没有选择任何无线电,则localStorage变量将重置为0,因为您有

  

var chanceoflive = 0;

如果要保留上次保存的值,则必须将该行替换为:

  

var chanceoflive = localStorage.chanceoflive;

答案 1 :(得分:0)

要回答有关LocalStorage的部分,只需将变量设置/获取为常规Javascript对象即可。更多信息:spherical harmonics and convolution