【问题标题】:Javascript Go To A URL If user input a specific number else go to another urlJavascript Go To A URL If user input a specific number else go to another url
【发布时间】:2015-01-18 04:54:46
【问题描述】:

如果用户在 id input-code 上输入的只是 1234abc,那么他将被重定向到 Google。如果他输入任何其他内容,那么他​​将被重定向到 Bing。

我的 HTML:

<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>

我的 Javascript:

    if (document.getElementById('input-code').value == '1234'){
        function btntest_onclick(){
            window.location.href = "http://www.google.com";
        }
        btntest_onclick()
    }else{
        function btntest_onclick(){
            window.location.href = "http://www.bing.com";
        }
        btntest_onclick()
    }

但是使用这段代码,当我转到我的页面时,它会立即将我重定向到 Bing。

【问题讨论】:

  • 你在 if 和 else 块中的函数声明很奇怪。发生这种情况是因为该函数在页面加载时立即执行。
  • 永远不要在 JavaScript 中有条件地声明函数。

标签: javascript html input


【解决方案1】:

您声明了两次相同的函数,因此它运行的是最后定义的版本。而且因为您的代码不在函数中或绑定到它在页面加载时运行的事件。试试这个:

function btntest_onclick(){
    if (document.getElementById('input-code').value == '1234') {
        window.location.href = "http://www.google.com";
    } else {
        window.location.href = "http://www.bing.com";
    }
};

【讨论】:

    猜你喜欢
    • 2022-12-26
    • 2022-12-02
    • 2022-12-02
    • 2022-11-09
    • 1970-01-01
    • 2022-12-01
    • 2022-12-01
    • 2022-12-02
    • 2022-12-26
    相关资源
    最近更新 更多