简体   繁体   English

仅使用函数来引用 DOM 元素

[英]Using functions only to reference DOM elements

I am learning JS from a book and the author constantly uses functions to reference DOM elements like this:我正在从一本书中学习 JS,作者经常使用函数来引用 DOM 元素,如下所示:

const navItems = () => document.querySelectorAll("nav li");

Why does he not just declare a variable like this:为什么他不只是声明一个这样的变量:

const navItems = document.querySelectorAll("nav li");

In my experience so far it makes little difference in the code, only that you have to call the functions by using the parentheses.以我迄今为止的经验,它对代码几乎没有什么影响,只是你必须使用括号来调用函数。 Is the first one considered better style for some reason?出于某种原因,第一个被认为是更好的风格吗?

const navItems = () => document.querySelectorAll("nav li");

navItems is a function and you would call it like navItems() whenever you want to get the elements. navItems是一个 function ,只要您想获取元素,就可以像navItems()一样调用它。

const navItems = document.querySelectorAll("nav li");

navItems here is a variable and this would not return live count if any li item is added after it's defined.这里的navItems是一个变量,如果在定义后添加任何li项目,则不会返回实时计数。

In sites that maintain the same content, there would be no difference between the two.在保持相同内容的网站中,两者之间没有区别。 However, in more complicated sites that might add elements dynamically after the page is loaded, the first approach would have the updated values while the second would not.但是,在更复杂的站点中,可能会在页面加载后动态添加元素,第一种方法将具有更新的值,而第二种方法则不会。 The first would only be better style if new elements are added.如果添加新元素,第一个只会是更好的样式。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM