簡體   English   中英

如果輸入標簽旁邊有更多按鈕,當按下“Enter”鍵時,如何在 JavaScript 中獲取 input.value?

[英]How to get input.value in JavaScript when the “Enter” key is pressed if I have more buttons next to the input tag?

這里我有一些代碼。 當我按下回車鍵時,我正在嘗試使用 JavaScript 獲取 input.value。 如果我刪除第一個按鈕而不是它正在工作,但是如果我留下這樣的代碼,或者如果我將第一個按鈕放在輸入標簽之前 - 它不起作用。

 const todoInput = document.querySelector(".todo-input"); const submit = document.querySelector(".addBtn"); submit.addEventListener("click", () => { console.log(todoInput.value); })
 <div class="todo-input-container"> <form class="input-form"> <input type="text" class="todo-input" placeholder="Add task..." /> <button class="btn flagBtn inputFlagBtn"> <span> <i class="far fa-flag"></i> </span> </button> <button class="btn addBtn" type="submit"> <span> <i class="fas fa-plus-circle"></i> </span> </button> </form> </div>

為什么只有當我從 html 中刪除第一個按鈕時,按“Enter”鍵才能得到 todoInput.value? 我需要做哪些調整才能使其與兩個按鈕一起使用?

如果只有一個提交按鈕,在輸入字段中按 Enter 只會自動提交表單。

您的標志按鈕也是一個提交按鈕,因為這是沒有type屬性時的默認設置。 如果它不應該是提交按鈕,請將type="button"添加到它。

 const todoInput = document.querySelector(".todo-input"); const submit = document.querySelector(".addBtn"); submit.addEventListener("click", () => { console.log(todoInput.value); })
 <div class="todo-input-container"> <form class="input-form"> <input type="text" class="todo-input" placeholder="Add task..." /> <button class="btn flagBtn inputFlagBtn" type="button"> <span> <i class="far fa-flag"></i> </span> </button> <button class="btn addBtn" type="submit"> <span> <i class="fas fa-plus-circle"></i> </span> </button> </form> </div>

您可以在 Input 字段上添加 keydown 事件偵聽器,這樣當用戶單擊輸入元素,鍵入內容,然后按 Enter 時,應該觸發事件偵聽器。

    const todoInput = document.querySelector(".todo-input");
    const submit = document.querySelector(".addBtn");
    
    submit.addEventListener("click", () => {
      console.log(todoInput.value);
    });


   //jQuery
   $("input").on("keydown", function (e) {
        if (e.keyCode == 13) { //13 is keyCode for Enter key
            e.preventDefault(); //look this up
            console.log(todoInput.value);
        }
    });

暫無
暫無

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

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