简体   繁体   English

我想使用这两个事件进行搜索:按键和鼠标单击,但它们似乎无法协同工作

[英]I want to search using both events: Keypress and Mouse click but they don't seem to be working together

I'm new to Javascript, currently making a weather app.我是Javascript的新手,目前正在制作天气应用程序。 I am trying to make a search using both keypress and click, but it does not seem to work together.我正在尝试使用按键和点击进行搜索,但它们似乎无法协同工作。 I have added two event listeners to the button used for searching.我向用于搜索的按钮添加了两个事件侦听器。 On click seems to work if I comment out the keypress code.如果我注释掉按键代码,则单击似乎有效。 As soon as I add the keypress section, I'm unable to make a search using both keypress and click.一旦我添加了按键部分,我就无法同时使用按键和点击进行搜索。

const api = {
      key: "48f26e932d82012fa8f78fca8da09da8",
      base: "https://api.openweathermap.org/data/2.5/",
    };
    
    ***const search = document.querySelector(".search");
    const btn = document.querySelector(".btn");
    btn.addEventListener("click", getInput);
    btn.addEventListener("keypress", getInput);
    
    function getInput(event) {
      event.preventDefault();
      if (event.type == "click") {
        getData(search.value);
        console.log(search.value);
      }
    }
    
    function getInput(event) {
      if (event.keyCode == 13) {
        getData(searchbox.value);
        console.log(search.value);
      }
    }***
    
    function getData() {
      fetch(`${api.base}weather?q=${search.value}&units=metric&appid=${api.key}`)
        .then((response) => {
          return response.json();
        })
        .then(displayData);
    }
    
    function displayData(response) {
      // console.log(response);
      if (response.cod === "404") {
        const error = document.querySelector(".error");
        error.textContent = "Please enter a valid city";
        search.value = "";
      } else {
        const city = document.querySelector(".city");
        city.innerText = `${response.name}, ${response.sys.country}`;
    
        const today = new Date();
        const date = document.querySelector(".date");
        date.innerText = dateFunction(today);
    
        const temp = document.querySelector(".temp");
        temp.innerHTML = `${Math.round(response.main.temp)} <span>°C</span>`;
    
        const weather = document.querySelector(".weather");
        weather.innerText = `${response.weather[0].main}`;
    
        const tempRange = document.querySelector(".temp-range");
        tempRange.innerText = ` ${Math.round(response.main.temp_min)}°C / ${Math.round(
          response.main.temp_max
        )}°C`;
    
        const weatherIcon = document.querySelector(".weather-icon");
        const iconURL = "http://openweathermap.org/img/w/";
        weatherIcon.src = iconURL + response.weather[0].icon + ".png";
    
        search.value = "";
      }
    }
    
    function dateFunction(d) {
      let months = [
        "Jan",
        "Feb",
        "Mar",
        "Apr",
        "May",
        "June",
        "July",
        "Aug",
        "Sep",
        "Oct",
        "Nov",
        "Dec",
      ];
      let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    
      let day = days[d.getDay()];
      let date = d.getDate();
      let month = months[d.getMonth()];
      let year = d.getFullYear();
    
      return `${day}, ${date} ${month} ${year}`;
    }

The keypress event fires when a key is pressed inside of that element like for example on an <input> it would fire if you typed inside the input. keypress事件在该元素内按下某个键时触发,例如在<input>上,如果您在输入内键入,它会触发。

In this case you're adding the listener to the button.在这种情况下,您要将侦听器添加到按钮。 In order to get it to register when you want it I'd add it to the search input like so:为了让它在你需要的时候注册,我会像这样将它添加到搜索输入中:

search.addEventListener("keypress", getInput);

Here is a working demo:这是一个工作演示:

 let search = document.getElementById("search"); let submit = document.getElementById("submit"); function getData() { console.log("Fetching Data"); } submit.addEventListener("click", getData); search.addEventListener("keypress", (event) => { if(event.keyCode === 13) { getData(); } });
 <input type="text" id="search"/> <button id="submit">Search</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 监听 iframe 内的鼠标点击和按键事件 - Listen for mouse click and keypress events within iframe Safari: <label>元素中的</label> SVG <label>似乎不适用于“点击”事件</label> - Safari: SVG in <label> elements don't seem to work with “click” events 在KineticJS中,在使用css3旋转的画布上,事件似乎无法正常工作 - In KineticJS, on a canvas rotated using css3, the events don't seem to be working properly Javascript Change和Click事件都不会触发 - Javascript Change and Click events don't both fire 在angularjs测试中使用element.triggerHandler()进行粘贴和按键事件似乎没有效果 - Using element.triggerHandler() in angularjs tests for paste and keypress events doesn't seem to have an effect 按键和鼠标事件 - Keypress and mouse events 处理鼠标单击和键控或按键事件(非修饰键) - Handling events for mouse click and keydown or keypress (for non-modifier keys) 网页上的鼠标行为–我不想标记文本 - Mouse Behavior on a WebPage – I don't want text being marked YUI 事件似乎不能递归地工作 - YUI events don't seem to work recursively 如果我不想等待2种方法,但都等待两种方法完成怎么办 - What if I don't want to await 2 methods but wait for both to finish
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM