簡體   English   中英

javascript在按下按鈕或返回鍵時從輸入轉到URL

[英]javascript go to URL from input on button press or return key

我有一個帶有輸入字段的頁面,我想將用戶發送到他們在輸入中輸入的 URL,並在末尾附加 -.html。 我的 HTML 如下:

<form name="codeform"> 
<input type="text" id="code" name="code" autofocus>
</form>

<a href="#" class="button" id="submit">SUBMIT</a>

還有我的 javascript:

$('#submit').click(function () { location.href = window.document.codeform.code.value + '.html'; });

當用戶單擊按鈕時,腳本按預期工作並且用戶轉到該頁面。 但我也希望在按下返回鍵時執行腳本。 現在,當按下返回鍵時,它會嘗試提交表單,我最終得到一個查詢字符串。

無論按下按鈕還是返回鍵,將用戶發送到頁面的最佳方式是什么?

因為您的a.button在表單之外,所以您也需要向表單和a.button添加觸發器。 然后只需檢測Enter keycode ,就完成了。

 $('form').submit(function(e) { e.preventDefault(); console.log(window.document.codeform.code.value + '.html') }); $('form').keydown(function(e) { if (e.which == 13) { console.log(window.document.codeform.code.value + '.html') } }); $('#submit.button').click(function() { console.log(window.document.codeform.code.value + '.html') });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <form name="codeform" id="codeform"> <input type="text" id="code" name="code" autofocus> </form> <a href="#" class="button" id="submit">SUBMIT</a>

您可以添加一個僅在輸入時運行的 keydown 偵聽器(鍵碼 13),然后阻止默認的表單提交操作:

$('#submit').click(function () { location.href = window.document.codeform.code.value + '.html'; });
$('#code').keydown(function (event) {
    if(event.which==13){
        event.preventDefault();//prevents form submission
        location.href = window.document.codeform.code.value + '.html';
    }
});

由於您將邏輯附加到按鈕 click() 事件,您可以簡單地將 keypress() 事件附加到輸入框以隨后執行按鈕單擊。

$("#code").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $('#submit').click();       
    }
});

但是,為了整潔,我通常更喜歡將邏輯從 click 事件移動到一個單獨的函數中,並從 click() 和 keypress() 事件中調用該函數。

暫無
暫無

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

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