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使用,则无需将其放入函数中。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…