Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

javascript - 我是否必须将事件监听器放入Vanilla JS中的函数中?(Do I have to put event listener in a function in vanilla js?)

Do I have to put event listeners in a function like in the example below?

(我是否必须将事件侦听器放在以下示例中的函数中?)

What's the point of putting it in a function that fires anyway?

(将其放在无论如何都会触发的函数中有什么意义?)

loadEventListeners();

function loadEventListeners() {
    // Add task event
    form.addEventListener('submit', addTask);
}

Why shouldn't I just put event listener in a global scope like this?:

(为什么我不应该将事件侦听器放在这样的全局范围内?)

form.addEventListener('submit', addTask);
  ask by Ermek Barmashev translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The purpose in doing it that way is to make sure the element you are attaching the listener to is loaded into the page.

(这样做的目的是确保将要附加侦听器的元素加载到页面中。)

In some cases, there may be a delay in that so people will have an "onload" event occur first.

(在某些情况下,可能会有延迟,因此人们将首先发生“加载”事件。)

For example, one may wish to have a click event happen on an image but the image may not be downloaded by the time the javascript gets loaded and executed in the page/document.

(例如,可能希望在图像上发生单击事件,但是在页面/文档中加载javascript并执行javascript时可能无法下载该图像。)

So you don't need to put it into a function if you are sure that form element, in your case, will be loaded and available to javascript to use.

(因此,如果您确定表单元素将被加载并可供javascript使用,则无需将其放入函数中。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...