如何使用事件侦听器获取搜索框值并将其记录下来


const searchBtn = document.getElementById("searchBtn");
const searchBar = document.getElementById("searchBar");
let searchQuery;
searchBar.addEventListener("keydown", (e) => {
if (e.key == "Enter" && searchBar.value != "") {
location.href = 'pages/results/results.html';
searchQuery = searchBar.value;
}
// get value entered and show on results.html
// results for: "query"
})
console.log(searchQuery); // not working

这会记录未定义的日志,因为事件循环一直在进行。我该如何等待用户按enter键,然后记录该值。我不想把console.log(searchQuery)放在函数中。提前谢谢。

您需要将console.log函数移动到事件处理程序内部,以便在触发事件处理程序时运行。现在,console.log函数在加载脚本时运行一次(记录undefined(,但没有任何东西可以再次触发它。试试这个:

const searchBtn = document.getElementById("searchBtn");
const searchBar = document.getElementById("searchBar");
let searchQuery;
searchBar.addEventListener("keydown", (e) => {
if (e.key == "Enter" && searchBar.value != "") {
location.href = 'pages/results/results.html';
searchQuery = searchBar.value;
}

console.log(searchQuery)
})

或者像这样,如果你只想在按下键时激发它&searchBar.value:

const searchBtn = document.getElementById("searchBtn");
const searchBar = document.getElementById("searchBar");
let searchQuery;
searchBar.addEventListener("keydown", (e) => {
if (e.key == "Enter" && searchBar.value != "") {
location.href = 'pages/results/results.html';
searchQuery = searchBar.value;
console.log(searchQuery)
}
})

最新更新