簡體   English   中英

輸入代碼后重定向到網頁

[英]Redirect to a webpage after giving a code

僅當輸入的代碼正確時,我才需要重定向到鏈接。 因此,概念是該人輸入了1234之類的代碼並轉到a.com,但是如果有人不編寫該代碼,則他們不會去任何地方

我嘗試了下面的代碼,但沒有任何效果。 我將網站名稱更改為a.com作為目標,將b.com作為重定向到a.com的網站

<body>
<input type="text" placeholder="Enter Your Code" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter Your Code'" maxlength="10" id="input-code">
<p><a href="#" class="btn" onclick="return btntest_onclick()">VERIFY  NOW</a></p>

<script>
if (document.getElementById('input-code').value == '1234'){
    function btntest_onclick(){
        window.location.href = "a.com";
    }
    btntest_onclick()
}else{
    function btntest_onclick(){
        window.location.href = "b.com";
    }
    btntest_onclick()
}

我希望輸入代碼1234進入a.com,但不會發生

您可以執行以下操作:

的HTML

<a href="#" class="btn" onclick="btntest_onclick()"></a>

將if語句移到函數內部

的JavaScript

function btntest_onclick(){
    if (document.getElementById('input-code').value == '1234'){
        window.location.href = "a.com";
    } else {
        window.location.href = "b.com";
    }
}

但是就像我在評論中說的那樣,通常不檢查此類客戶端,因為它很容易被篡改。

通過在用戶輸入正確的代碼時設置href ,可以輕松實現更好的解決方案。

我建議這種方法,避免使用內聯onclick屬性,而使用更具語義的<button>元素而不是鏈接。

 const buttonEl = document.querySelector('.btn'); const inputEl = document.querySelector('#input-code'); buttonEl.addEventListener("click", evt => { if (inputEl.value == '1234') { window.location.href = 'http://a.com'; } }); 
 <input id="input-code" type="text" placeholder="Enter Your Code" maxlength="10"> <p><button class="btn">Verify Now</button></p> 

有關為什么我們嘗試避免使用onclick更多信息,請參見為什么在HTML中使用onClick()是一種不好的做法?

正如其他人已經提到的那樣,這不是驗證表單的安全方法,並且容易被精明的用戶繞開。 如果安全性是您特定用例的考慮因素,則應使用服務器端驗證。

暫無
暫無

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

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