[英]how to redirect a html page in javascript
我正在處理我的注冊表的 Javascript 頁面。 如果所有內容都已填寫,我只是無法弄清楚如何使頁面重定向到另一個頁面。
document.getElementById("check").onclick = function() {
let allAreFilled = true;
document.getElementById("myForm").querySelectorAll("[required]").forEach(function(i) {
if (!allAreFilled) return;
if (!i.value) allAreFilled = false;
if (i.type === "radio") {
let radioValueCheck = false;
document.getElementById("myForm").querySelectorAll(`[name=${i.name}]`).forEach(function(r) {
if (r.checked) radioValueCheck = true;
})
allAreFilled = radioValueCheck;
}
})
if (!allAreFilled) {
alert('Fill all the fields');
}
else {
window.location.replace("http://www.w3schools.com");
}
};
我正在為同樣可能出現的問題提供我的示例腳本,希望這會有所幫助
HTML
<pre>
<!DOCTYPE HTML>
<html>
<body>
<p id=P >Fill in all checkboxes</p>
<form>
<input type=radio />
<label>Check 1</label>
<input type=radio />
<label>Check 2</label>
<input type=radio />
<label>Check 3</label>
</form>
</body>
</html>
</pre>
JavaScript
window.onload = () =>
{
var radio = document.querySelectorAll('[type=radio]'),
p = document.getElementById("P");
radio.forEach(
function(i)
{
i.onchange = () =>
{
var checked = document.querySelectorAll("[type=radio]:checked"),
leftover = radio.length - checked.length;
p.innerHTML = "leftover checkbox " + leftover;
if(radio.length == checked.length)
{
alert("All checked");
window.location.href = "https://ilhamb.com/";
}
}
}
)
}
使用 window.location.href 在同一選項卡/窗口中重定向或使用 window.open() 在新選項卡/窗口中重定向。
正如 Quentin 指出的那樣,您已經在使用適當的方式進行重定向。 我可以建議打開控制台並檢查是否有控制台錯誤嗎? 還要確保您的程序通過使用瀏覽器斷點或控制台日志實際到達重定向。
這段代碼
window.location = "w3schools.com"
或者
window.location.href = "w3schools.com"
應該做
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.