我想重定向到包含JavaScript中两个单独基本数学功能的两个页面之一。这些页面应链接到给出的两个无线电按钮之一,并在用户单击"确定"按钮上进行了重定向。
function myFunction() {
var x = document.getElementById("x");
var y = document.getElementById("y")
if (x.checked = true); {
//* redirect link when Okay button is click
} else(y.checked = true); {
//* redirect link when Okay button is clicked
}
}
<!DOCTYPE html>
<html>
<body>
<p>What would you like to convert?</p>
<form action="/action_page.php">
<input type="radio" name="converter" value="grams" id="x">Grams to ounces
<br>
<input type="radio" name="converter" value="ounces" id="y">Ounces to grams
<br>
<br>
<input type="button" onclick="myFunction()" value="Okay!">
<br>
</form>
</body>
</html>
您应该使用一个选择框,对您来说更容易
<select id="myChoice">
<option value="grams">grams</option>
<option value="ounces">ounces</option>
</select>
和您的JS
function myFunction() {
var theChoice = document.getElementById("myChoice")
switch (theChoice.value){
case 'grams':
//redirect;
break;
case 'ounces':
//redirect
break;
}
这很简单,只需创建一个类型A的元素,将属性放置并模拟click()
到重定向
这是笔示例:https://codepen.io/lucassoomago/pen/ybkwjx
下面的示例不会重定向,因为堆栈溢出不允许,如果您想查看重定向,请使用上面的链接
function myFunction() {
var x = document.getElementById("x");
var y = document.getElementById("y")
var a = document.createElement("a");
if (x.checked == true)
{
a.setAttribute('href', 'https://www.google.com');
a.setAttribute('target', 'blank');
}else if (y.checked == true)
{
a.setAttribute('href', 'https://www.youtube.com');
a.setAttribute('target', 'blank');
}
a.click()
}
<p>What would you like to convert?</p>
<form action="/action_page.php">
<input type="radio" name="converter" value="grams" id="x">Grams to
ounces<br>
<input type="radio" name="converter" value="ounces" id="y">Ounces to
grams<br>
<br>
<input type="button" onclick="myFunction()" value="Okay!">
<br>
</form>
以下内容将检查复选框是否被打勾,然后将您重定向到定义的URL。如果您的示例中都没有选择复选框,我已经使用了else if
,因为else
会将您重定向到位置Y。
<form action="/action_page.php">
<input type="radio" name="converter" value="grams" id="x">Grams to
ounces<br>
<input type="radio" name="converter" value="ounces" id="y">Ounces to
grams<br>
<br>
<input type="button" onclick="myFunction()" value="Okay!">
<br>
</form>
<script>
function myFunction() {
var x = document.getElementById("x");
var y = document.getElementById("y")
if (x.checked)
{
window.location.replace("url");
}
else if (y.checked)
{
window.location.replace("url");
}
}
</script>