开发者

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

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

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

The code 开发者_StackOverflowabove works, while this one does not:

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

Why not?


When you define the callback as hello(), the function is actually being called right then, and the result is what is assigned to be 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 parameters to the function called within the callback) you can wrap your function in an anonymous function:

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


Try this (notice no parentheses after hello):

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

Whenever you pass a function to another function to be called later (this is known as a callback), you omit the parentheses because you don't want the function to be called now, you want the other function to call it later. Think of it as a way of giving the name of the function to be called later.


hello() calls the function immediately and supplies it return value (undefined) as the parameter of load. You need to provide a reference to hello to load instead:

 $('#playerslot').html( '' ).load('player/',hello);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜