开发者

jQuery functions only work inside .ready()

I'm still new 开发者_运维技巧to jQuery and I'm wondering how come the jQuery functions called inside .ready() work just fine but not outside?

For example, this would work:

$(document).ready(function() {
    $('#field1').click(function() {
        $('#result').load('/random_post #post');
    });
});

But this won't:

$('#field1').click(function() {
    $('#result').load('/random_post #post');
});


You cannot access the DOM until the document is fully parsed and the DOM constructed. That includes modifying any elements – such as #field1 and #result.

Since $(document).ready(..) is long and may be hard to remember, you can also use the short form $(onReadyFunction), i.e.

$(function() {
    $('#field1').click(function() {
        $('#result').load('/random_post #post');
    });
});

By the way, jQuery does no magic here: It just registers your function to be called when DOMContentLoaded (or equivalent) event is triggered by the parsing and construction of the DOM tree.


How and if it works will depend on the order of which scripts and elements are laid out in your HTML, and it might also be affected by parameters outside your control (e.g. how the browser is programmed to behave).

I 'd hazard a guess that this script appears in your page before the element with id="field1" that gets a click handler added; this causes the script to run and find no such element in the document tree (yet). The element gets added after the script runs, which is why jQuery finds it just fine after the whole document has loaded.

If you move this script at the very end of your page it should work (although of course the correct solution is to use the document ready event, as in your first snippet).


The ready function is executed when the dom tree has been created. You get an error in your second piece of code because the dom tree element with id filed1 has not been created yet, i.e. the page hasn't loaded yet.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜