Why can't I access newly loaded DOM elements in the .load () callback function?

I am new to JavaScript and jQuery, so I think I have some kind of misunderstanding of how this stuff should work. What I am doing is loading some html via .load (), then I call the previously defined function as a callback function. This function does not do the same as when I define it directly in place:

$(document).ready(function(){ $('#playerslot').html( '' ).load('player/',function(){ $('#new_element').replaceWith('Hello World!') }); }); 

The above code works, but it doesn't:

 function hello(){ $('#new_element').replaceWith('Hello World!') }); $(document).ready(function(){ $('#playerslot').html( '' ).load('player/',hello()); }); 

Why not?

+4
source share
3 answers

When you define a callback as hello() , the function is actually called right then, and the result is what is assigned to the callback. Instead, you should either do

 $(document).ready(function(){ $('#playerslot').html( '' ).load('player/', hello); }); 

or (and this is necessary if you need to pass the parameters of the function called in the callback), you can wrap your function with an anonymous function:

 $(document).ready(function(){ $('#playerslot').html( '' ).load('player/', function() {hello()}); }); 
+3
source

Try this (don't notice parentheses after hello ):

 $(document).ready(function(){ $('#playerslot').html( '' ).load('player/', hello); }); 

Whenever you pass a function to another function that will be called later (this is called a callback), you omit the parentheses because you do not want the function to be called now, you want the other function to call it later, Think about it how about a way to name the function to be called later.

+2
source

hello() calls the function immediately and supplies its return value ( undefined ) as the load parameter. Instead, you need to point the hello link to load :

  $('#playerslot').html( '' ).load('player/',hello); 
+1
source

Source: https://habr.com/ru/post/1341162/


All Articles