首页 > 解决方案 > 使用事件监听器在 Javascript 中提交表单不会触发获取请求

问题描述

我有一个搜索表单,我想从中发送对 API 的调用。我知道我的功能正在运行,因为在提交时,我的控制台日志会触发。此外,在控制台中,如果我调用我的function search("mytermhere")我会从 API 得到响应,但从表单事件中触发我的搜索功能将不起作用。请帮忙!

HTML:

       <!DOCTYPE html>
<html lang="en">




<head>

    <link href="https://fonts.googleapis.com/css?family=Liu+Jian+Mao+Cao|Raleway&display=swap" rel="stylesheet">

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/solid.min.js">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>Document</title>
</head>

<body>
    <div class="background">
        <div class="overlay">
            <h1 class="title">
                Visual Vibes
            </h1>
            <h2>search images</h2>
            <form class="search-form" type="submit">
                <input label="search" class="input" type="text" placeholder="&#xf002" value="">
            </form>
        </div>
    </div>
    <script src=" script.js "></script>
</body>

</html>

JS:

const input = document.querySelector(".input");
let searchTerm = input.value;
const form = document.querySelector(".search-form");

function search(searchTerm) { //does not run when called by event listener
  let url = `${URL}&query=${searchTerm}`;
  return fetch(url)
    .then(response => response.json())
    .then(result => {
      return result.results;
      console.log(results.results);
    });
}

input.addEventListener("focus", function(e) {
  e.preventDefault();
  console.log(input);
  input.style = "font-family: 'Raleway', sans-serif";
  input.placeholder = "";
});
input.addEventListener("blur", function(e) {
  e.preventDefault();
  console.log(input);
  input.style = "font-family: FontAwesome";
  input.value = "";
  input.placeholder = "\uf002";
});
form.addEventListener(
  "submit",
  function(e) {
    let searchTerm = input.value;
    console.log(searchTerm); //outputs value in input in console
    e.preventDefault();
    console.log("hi"); //outputs in console when form submitted
    search(searchTerm); //this function does not run
  },
  false
);

编辑:更新以包含完整代码

标签: javascripthtmlfunctionsearchdom-events

解决方案


您的问题出在表单 HTML 代码中。

表单标签没有“类型”属性。如果您打算添加一个按钮来提交表单,请这样做:

<input type="submit" value="Submit" />

此外,据我所知,您的“searchTerm”变量无效。没有“input.value”。您需要将“名称”属性添加到两者,或者将“id”属性添加到输入文本框以检索搜索词。

检索带有 ID 的搜索词:

document.getElementById("id").value;

检索带有名称的搜索词:

document.nameOfForm.nameOfTextbox.value;

如果您想让表单“无按钮”可提交,请将位置设置为“绝对”并将其隐藏在某处,如下所示:

<input type="submit" style="position: absolute; left: -9999px"/>

推荐阅读