[英]Is there a reason to simplify this and how? (JavaScript enter key function on search field)
I've got a simple function that waits for the page to load and then listens for a keyup on a input search field. 我有一个简单的函数,等待页面加载,然后在输入搜索字段上侦听键入内容。 This works without fail, but I think that creating functions in the global scope save on processing and help write less redundant code.
这可以正常工作,但是我认为在全局范围内创建函数可以节省处理时间并有助于编写更少的冗余代码。
//Enter button functionality while search field is focused
window.onload = function() {
var termsField = document.getElementById('search-terms');
var searchButton = document.getElementById('search-button');
termsField.addEventListener("keyup", function(event){
event.preventDefault();
if (event.keyCode === 13){
searchButton.click();
}
})
}
I tried: 我试过了:
//Enter button functionality while search field is focused
function checkKeyCode(event, buttonVariable){
event.preventDefault();
if (event.keyCode === 13){
buttonVariable.click();
}
}
window.onload = function() {
var termsField = document.getElementById('search-terms');
var searchButton = document.getElementById('search-button');
termsField.addEventListener("keyup", checkKeyCode(event, searchButton));
}
However, this didn't seem to work as I don't think the addEventListener
allows for passing arguments into functions. 但是,这似乎没有用,因为我认为
addEventListener
不允许将参数传递给函数。
My question: Should I try and simplify this, and if so, what are some ideas for implementing a 'cleaner' or 'better' solution? 我的问题:我是否应该尝试简化此过程,如果是,那么实现“清洁”或“更好”解决方案的一些想法是什么? I would appreciate it if you could leave most of the code to me and just help with an working idea, so that I can get the experience.
如果您可以将大部分代码留给我,并仅提供一个可行的想法,以便获得经验,我将不胜感激。 Thanks!
谢谢!
Because you're using only once termsField
and searchButton
variables, it's not necessary to store them. 由于只使用一次
termsField
和searchButton
变量,因此不需要存储它们。
You can " simplify " like this 您可以像这样“ 简化 ”
// Enter button functionality while search field is focused
function checkKeyCode(event){
event.preventDefault();
if (event.keyCode === 13){
document.getElementById('search-button').click();
}
// or, in one line
// if (event.keyCode === 13) document.getElementById('search-button').click();
}
window.onload = function() {
document.getElementById('search-terms').addEventListener("keyup", checkKeyCode);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.