DWQA QuestionsCategory: ProgramDoes the click event in jQuery have to be placed in $(document). Ready (function () {}) to work? Why?
esolve asked 1 month ago

Does the click event in jQuery have to be placed in $(document). Ready (function () {}) to work? Why?
What’s the difference between putting it here and not?

Song of strangers replied 1 month ago

This is equivalent to the execution of JS after the DOM structure has been loaded. You can put JS in the head. If you don’t, you need JS statements after the DOM you click, that is, the nodes you click in HTML must be in front of JS, usually before < / body >

9 Answers
vitech answered 1 month ago

There are two possible failures when you put it outside. In short, you monitor a click event. If the monitoring succeeds, the element has been loaded in the current dom
For example, your JS reference will be invalid before the element appears, such as

<script>
$('#abc').click(funcition(){...});
</script>
<div id="abc"></div>

The other is that you may dynamically generate some elements after the page is loaded, that is to say, this element is not in HTML at first. In this case, if the click listen statement is executed earlier than the generated statement, it will also be invalid.
In a word, $(document). Ready (function() {…}) internal statements will ensure that they are executed after DOM loading. Generally speaking, as long as your JS is written / referenced at the end of the page and there is no possibility of dynamic generation, it is OK to write them outside.

North Area answered 1 month ago

It’s not necessary to imitate them, because they wait for the elements to be loaded before binding and adding events. It is invalid to add events before the elements are loaded

The songs of strangers answered 1 month ago

Page loading is from the beginning to the end. When parsing JS, if the DOM used in JS does not appear before this section of JS, an error will be reported. $(document). Ready (function() {}) is to let your DOM load before parsing JS

Spongebob answered 1 month ago

Its events are not useful until the page is loaded. Just like you eat, you have to have food first.

zejuan answered 1 month ago

It is not necessary to put it in HTML. If the element is generated by JS, it needs to be put in it

tain335 replied 1 month ago

ha-ha??

To be a big man answered 1 month ago

Not necessary to bind directly`
a.clcik(funxtion(){

 ...

})

jweiamybz answered 1 month ago

The function of the sentence $(document). Ready (function() {}) is to execute the method in the page when it is loaded. It is similar to $(function() {}). If you write it directly on the page, you don’t need to add it. If you write it in a public JS file, you need to add it. Otherwise, it will not be executed

I am a wooden man answered 1 month ago

Not necessarily. It only needs a method to call outside

qiuwww answered 1 month ago

Try the on method to use the body agent for events for elements that are not loaded