开发者

Sync jQuery retrieving from the DOM

开发者 https://www.devze.com 2023-03-30 19:03 出处:网络
I have a personal scripting setup. What I do is write some javascript files in a folder, then a script takes care of joining all of them and minify them.

I have a personal scripting setup. What I do is write some javascript files in a folder, then a script takes care of joining all of them and minify them.

In two different files, I have this:

FILE 1:

...document ready...
$(this).attr('id', 'foo');
...

FILE 2:

...document ready...
$('#foo')开发者_C百科.append('<span>bar</span>');
...

The problem is, that when it tries to retrieve the #foo element, it doesn't find anything, most probably cause it's not created yet. Is there any way to sync this process, so it follows a more proper order? (First create, then append)

Thanks!


The "document ready" event cannot make sure in which order your functions are called. I think it would be better if you do not use the "document ready" event for the function in File 2.

Something like this should work:

File 2:

...on load of page/element...
'parent of foo'.bind('foo_inserted', 
                      function() { $('#foo').append('<span>bar</span>'); });

File 1:

...document ready...
'parent of foo'.attr('id', 'foo');
'parent of foo'.trigger('foo_inserted');

For more details see e.g. this page or the jQuery documentation.

0

精彩评论

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