簡體   English   中英

當某個條件為真時如何使用 javascript 重定向到另一個頁面

[英]how to redirect to another page when a certain condition is true using javascript

我是 javascript 的新手,我目前被困在這個問題上。 我需要根據某些移動的數量重定向到另一個頁面。 例如:如果找到所有對后的移動次數在 4 - 8 之間,您將被重定向到第 1 頁查看結果,10 - 16 在第 2 頁等等,但我關於結果的代碼仍然轉到第 1 頁。這是我的 js 代碼:

 function validate() {
  var clickHere = document.getElementById("terms");
  if(clickHere.checked){
    if(counterVal >= 4 || counterVal <=8){
      location.replace("https://www.w3schools.com/js/")
    }
    else{
      location.replace("https://javascript.info/")
    }
  }else{
    
    alertify.error('Click the checkbox first.')
  }

我一直在嘗試不同的方法來解決這個問題,但沒有運氣。 感謝您的幫助。

The simplest way to use JavaScript to redirect to a URL is to set the location property to a new URL using window.location.href . JavaScript 代碼如下所示: window.location.href = 'https://ExampleURL.com/'; 它是一個屬性,告訴您當前正在查看什么 URL。 設置一個新值,就是告訴瀏覽器加載新的 URL,類似於用戶單擊鏈接時會發生的情況。 您的 function 應該如下所示:

function validate() {
  var clickHere = document.getElementById("terms");
  if(clickHere.checked){
    if(counterVal >= 4 || counterVal <=8){
      window.location.href = "https://www.w3schools.com/js/"
    }
    else{
      window.location.href ="https://javascript.info/"
    }
  }else{
    
    alertify.error('Click the checkbox first.')
  }

從您的問題中,您提到for example: if the number of moves after you find all the pairs are between 4 - 8, you will be redirected to page 1 to see your result, 10 - 16 is on page 2 and so on, but my code regarding of result still goes to page 1

正如您提到的, countVal介於 4 到 8 之間,那么它將用於此鏈接https://www.w3schools.com/js/

但是在此,如果您提到的條件為counterVal <=4 如果 countVal 大於 8,則條件為真,這就是問題所在。

if(counterVal >= 4 || counterVal <=8){

你需要像這樣重寫它

if(counterVal >= 4 && counterVal <=8){

我希望這會很有用。

代碼必須是

if(counterVal >= 4 && counterVal <=8){
   window.location.href = "https://www.w3schools.com/js/1"
}else if(counterVal >= 10 && counterVal <=16){
   window.location.href = "https://www.w3schools.com/js/2"
}else{
  location.replace("https://javascript.info/")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM