首页 > 解决方案 > 无法通过 JavaScript 函数重定向 HTML 页面

问题描述

我正在使用 HTML、CSS 和 JavaScript 制作一个简单的决定你自己命运的游戏。我开始编写一个函数来检测他们想要选择的单选按钮中的选择,但是当我编写使用 JavaScript 的“location.replace”更改页面(HTML)的函数时,我无论选择什么按钮,都会收到相同的警报。

    <form>
      <input type="radio" name="choice" onclick="getRadioValue('A1')" value="A1" checked> Lorem ipsum dolor sit amet, consectetur adipiscing elit. <br>
      <input type="radio" name="choice" onclick="getRadioValue('A2')" value="A2"> Proin volutpat eros fringilla felis euismod laoreet a eu velit. <br>
      <input type="radio" name="choice" onclick="getRadioValue('A3')" value="A3"> Mauris orci mi, luctus in leo eget, facilisis imperdiet lacus. <br><br>
      <button type="button" onclick=choiceA()> Choose </button>
    </form>
var selectedButton = 'A1';
function getRadioValue(param){
    selectedButton = param;
    console.log(selectedButton);
}

function choiceA(){
  alert(selectedButton)
    if (selectedButton = 'A1') {
      alert("You selected the first button!");
      location.replace();
    } else if (selectedButton = 'A2') {
      alert("You selected the second button!");
      location.replace();
    } else {
      alert("You selected the third button!");
      location.replace();
    }
}

标签: javascripthtml

解决方案


您正在使用赋值运算符=。您应该使用比较运算符=====. 最好使用严格相等===

function choiceA(){
  alert(selectedButton)
    if (selectedButton === 'A1') {
      alert("You selected the first button!");
      location.replace();
    } else if (selectedButton === 'A2') {
      alert("You selected the second button!");
      location.replace();
    } else {
      alert("You selected the third button!");
      location.replace();
    }
}

您可以通过制作一个对象来使您的代码更好更短。

var selectedButton = 'A1';
function getRadioValue(param){
    selectedButton = param;
    console.log(selectedButton);
}

function choiceA(){
  const obj = {
    A1:'first',
    A2:'second'
  }
  alert(`You selected the ${obj[selectedButton] || 'third'} button`)
}
<form>
      <input type="radio" name="choice" onclick="getRadioValue('A1')" value="A1" checked> Lorem ipsum dolor sit amet, consectetur adipiscing elit. <br>
      <input type="radio" name="choice" onclick="getRadioValue('A2')" value="A2"> Proin volutpat eros fringilla felis euismod laoreet a eu velit. <br>
      <input type="radio" name="choice" onclick="getRadioValue('A3')" value="A3"> Mauris orci mi, luctus in leo eget, facilisis imperdiet lacus. <br><br>
      <button type="button" onclick=choiceA()> Choose </button>
    </form>


推荐阅读