javascript - 无法通过 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();
}
}
解决方案
您正在使用赋值运算符=
。您应该使用比较运算符==
或===
. 最好使用严格相等===
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>
推荐阅读
- gitlab - Gitlab CI runner 离线
- bash - Docker shell 脚本未按预期进行参数化
- swift - 为什么在遍历场景中的每个节点时会出现 EXC_BREAKPOINT?
- bash - 如何为 pyspark jupyter notebook 设置端口?
- postgresql - 在 plpgsql 中比较 bytea 和 bytea
- java - 擦除标签约束
- php - 我找不到我的 PHP 错误,它给了我一个 T_ELSE
- python - Pandas applymap函数在应用于太多列时删除行?
- javascript - How to translate ViewBox's coordinates to specific SVG element's center in Javascript (without libraries)
- java - CSS定位器选择反应的问题