无法通过JavaScript函数重定向HTML页面
我正在制作一个简单的决定你自己命运风格的游戏,只使用HTML、CSS和JavaScript。我开始编写一个函数来检测他们想要选择的单选按钮,但当我编写函数来使用JavaScript的location.replace更改页面HTML时,无论选择了什么按钮,我都会收到相同的警报 Lorem ipsum dolor sit amet,是一位杰出的献身者。 佩特罗斯·弗林利亚·菲利斯·尤斯莫德·拉奥里特是欧盟的一员。 莫里斯·奥奇·米,利奥·埃吉特的卢克图斯,设施不完善。 选择无法通过JavaScript函数重定向HTML页面,javascript,html,Javascript,Html,我正在制作一个简单的决定你自己命运风格的游戏,只使用HTML、CSS和JavaScript。我开始编写一个函数来检测他们想要选择的单选按钮,但当我编写函数来使用JavaScript的location.replace更改页面HTML时,无论选择了什么按钮,我都会收到相同的警报 Lorem ipsum dolor sit amet,是一位杰出的献身者。 佩特罗斯·弗林利亚·菲利斯·尤斯莫德·拉奥里特是欧盟的一员。 莫里斯·奥奇·米,利奥·埃吉特的卢克图斯,设施不完善。 选择 您正在使用赋值运算符=。
您正在使用赋值运算符=。您应该使用比较运算符==或==。最好使用严格平等=== 通过创建一个对象,可以使代码更好、更短 var selectedButton='A1'; 函数getRadioValueparam{ selectedButton=参数; console.LogSelected按钮; } 功能选择{ 常量对象={ A1:‘第一’, A2:“第二” } 警报`您选择了${obj[selectedButton]| |'third'}按钮` } Lorem ipsum dolor sit amet,是一位杰出的献身者。 佩特罗斯·弗林利亚·菲利斯·尤斯莫德·拉奥里特是欧盟的一员。 莫里斯·奥奇·米,利奥·埃吉特的卢克图斯,设施不完善。 选择
开关箱更适合这项工作。您也不需要存储选中的值。您可以只查询选中的元素 尽管它将与按钮上的内联事件处理程序一起工作。我建议在javascript中使用addEventListener函数来附加事件 功能选择{ var selectedValue=document.querySelector'input[name=choice]:checked'。值; 开关选择值{ 案例A1: 选择console.logA1; 打破 案例A2: 选择console.logA2; 打破 案例A3: 选择console.logA3; 打破 违约: //如果您决定添加第四个选项而忘记更新此函数,那么记录一些错误将是很好的。 有些事情出了严重的问题; } } Lorem ipsum dolor sit amet,是一位杰出的献身者。 佩特罗斯·弗林利亚·菲利斯·尤斯莫德·拉奥里特是欧盟的一员。 莫里斯·奥奇·米,利奥·埃吉特的卢克图斯,设施不完善。 选择
对于@SamsyTheUnicorn:在JS、C和许多语言中,如果selectedButton='A1'和selectedButton='A1'将始终执行相同的操作:变量selectedButton获得值'A1'
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();
}
}