Javascript 如何使用事件侦听器获取搜索框值并记录它

Javascript 如何使用事件侦听器获取搜索框值并记录它,javascript,Javascript,此日志未定义,因为事件循环一直在进行。我如何等待用户按enter键,然后记录之后的值。我不想将console.log(searchQuery)放在函数中。提前感谢。您需要在事件处理程序中移动console.log函数,以便在触发事件处理程序时运行它。现在,加载脚本时,console.log函数只运行一次(记录undefined),但无法再次触发它。试试这个: const searchBtn = document.getElementById("searchBtn"); con

此日志未定义,因为事件循环一直在进行。我如何等待用户按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;
    }
    // get value entered and show on results.html
    // results for: "query"
})

console.log(searchQuery); // not working
或者,如果您只想在按下Enter&
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)
})

这是一个范围问题,您无法避免在函数中使用console.log。您可以创建另一个函数并传递其值。
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)
    }
})