簡體   English   中英

使用 Javascript 中的按鈕防止默認輸入鍵

[英]Prevent default on enter key with a button in Javascript

我有我的 HTML 代碼:

<!DOCTYPE html>
<head>
  <script src="../req.js"></script>
  </head>


<link rel="stylesheet" href="style.css">
<html>

<body>
  <h1> Recipes founder</h1>
  <form class="example">
    <input id ="query" type="text" placeholder="Insert a recipe.." name="search" value="">
    <button id="searchRecipe" type="button" onkeydown="handler(e)" onclick="searchFile()"><i></i>Search</button>

  </form>
  <div id="content"></div>
</body>
</html>

以及與之關聯的我的js代碼:

function searchFile(e) {
  // enter must do the same
  const q = document.getElementById('query').value;
  const total_q = `Title%3A${q}%20OR%20Description%3A${q}%20OR%20web%3A${q}`
  fetch(
`http://localhost:8983/solr/recipe/select?indent=true&q.op=OR&q=${total_q}&rows=300`, { mode: 'cors' }

  ).then((res) => res.json())
      // Take actual json
      .then(({ response }) => appendData(response))
      .catch(function (err) {
          console.log(err)
      });
  }

function appendData(data) {
    // clear previous research
    document.getElementById("content").innerHTML = "";
    let docs = data.docs;
    // Take each element of the json file
    for (elem of docs) {
        var mainContainer = document.getElementById("content");
        // title recipe
        var a1 = document.createElement("a");
        a1.setAttribute("href", elem.url);
        var div = document.createElement("div");
        div.innerHTML = elem.Title;
        a1.appendChild(div);

        // insert image of recipe and link for page in website
        var a = document.createElement("a");
        a.setAttribute("href", elem.Image);
        var img = document.createElement("img");
        // img.setAttribute("href", elem.url);
        img.setAttribute("src", elem.Image);
        a.appendChild(img);

        // recipe description
        var p = document.createElement("p");
        p.innerHTML = elem.Description;
        // Insert elements in dev
        mainContainer.appendChild(a1);
        mainContainer.appendChild(p);
        mainContainer.appendChild(a);
        
    }
}


function handler(event) {
    if (event == "click") {
       searchFile();
    }
    else if ((event.keyCode || event.which) == 13){
        event.preventDefault();
        event.cancelBubble = true;
        event.returnValue = false;
        event.stopPropagation();
        event.preventDefault();

        searchFile();
    }
    else {
        console.log("Nothing")
    }
}

searchFile() 和 appendData() 做什么並不重要,因為它們有效。 目標是當用戶單擊搜索按鈕或按下回車鍵時,必須調用 searchFile()。 單擊搜索按鈕有效,但問題是當用戶單擊輸入時,它導航到 http://localhost:8000/?search=SOMETHING(取決於用戶插入的內容)。 我認為這是回車鍵的默認行為,我試圖使用不同的代碼來阻止它,但沒有任何效果。 我讀到,我們必須使用 onkeydown 而不是使用事件 onkeypress,但我仍然處於同樣的情況。 我也嘗試等待 DOM 被加載但什么也沒有。 有人對此有想法嗎?

  1. 刪除按鈕上的所有事件處理程序
  2. 使按鈕成為提交按鈕
  3. 在表單上使用提交事件(如果表單提交是通過在輸入中輸入單擊按鈕在按鈕上按下輸入來觸發的,則會觸發該事件)
  4. 阻止默認事件行為(因此表單數據不會提交到瀏覽器導航到的 URL)
  5. 不要費心做任何測試來試圖弄清楚它是點擊還是其他東西,如果提交了表單,所有這些都很重要。

 const submitHandler = (event) => { event.preventDefault(); alert("You can do your ajax search here"); }; document.querySelector('.example').addEventListener('submit', submitHandler);
 <form class="example"> <input id="query" type="text" placeholder="Insert a recipe.." name="search" value=""> <button>Search</button> </form>

暫無
暫無

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

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