后面的 jQuery 函数

在 jQuery.append完成之后如何调用函数?

这里有一个例子:

$("#root").append(child, function(){
// Action after append is completly done
});

问题: 当附加一个复杂的 DOM 结构时,在附加函数回调中计算根元素的新大小是错误的。假设 DOM 仍然没有完全加载,只有添加的复杂 DOM 的第一个子元素是。

175159 次浏览

the Jquery append function returns a jQuery object so you can just tag a method on the end

$("#root").append(child).anotherJqueryMethod();
$('#root').append(child);
// do your work here

Append doesn't have callbacks, and this is code that executes synchronously - there is no risk of it NOT being done

$('#root').append(child).anotherMethod();

You've got many valid answers in here but none of them really tells you why it works as it does.

In JavaScript commands are executed one at a time, synchronously in the order they come, unless you explicitly tell them to be asynchronous by using a timeout or interval.

This means that your .append method will be executed and nothing else (disregarding any potential timeouts or intervals that may exist) will execute until that method have finished its job.

To summarize, there's no need for a callback since .append will be run synchronously.

I think this is well answered but this is a bit more specific to handling the "subChild_with_SIZE" (if that's coming from the parent, but you can adapt it from where it may be)

$("#root").append(
$('<div />',{
'id': 'child'
})
)
.children()
.last()
.each(function() {
$(this).append(
$('<div />',{
'id': $(this).parent().width()
})
);
});

$.when($('#root').append(child)).then(anotherMethod());

Well I've got exactly the same problem with size recalculation and after hours of headache I have to disagree with .append() behaving strictly synchronous. Well at least in Google Chrome. See following code.

var input = $( '<input />' );
input.append( arbitraryElement );
input.css( 'padding-left' );

The padding-left property is correctly retrieved in Firefox but it is empty in Chrome. Like all other CSS properties I suppose. After some experiments I had to settle for wrapping the CSS 'getter' into setTimeout() with 10 ms delay which I know is UGLY as hell but the only one working in Chrome. If any of you had an idea how to solve this issue better way I'd be very grateful.

I have another variant which may be useful for someone:

$('<img src="http://example.com/someresource.jpg">').load(function() {
$('#login').submit();
}).appendTo("body");

I know it's not the best solution, but the best practice:

$("#root").append(child);


setTimeout(function(){
// Action after append
},100);

I encountered this issue while coding HTML5 for mobile devices. Some browser/device combinations caused errors because .append() method did not reflect the changes in the DOM immediatly (causing the JS to fail).

By quick-and-dirty solution for this situation was:

var appint = setInterval(function(){
if ( $('#foobar').length > 0 ) {
//now you can be sure append is ready
//$('#foobar').remove(); if elem is just for checking
//clearInterval(appint)
}
}, 100);
$(body).append('<div>...</div><div id="foobar"></div>');

Yes you can add a callback function to any DOM insertion:
$myDiv.append( function(index_myDiv, HTML_myDiv){ //.... return child })

Check on JQuery documentation: http://api.jquery.com/append/
And here's a practical, similar, example: http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_prepend_func

I ran into a similar problem recently. The solution for me was to re-create the colletion. Let me try to demonstrate:

var $element = $(selector);
$element.append(content);


// This Doesn't work, because $element still contains old structure:
$element.fooBar();


// This should work: the collection is re-created with the new content:
$(selector).fooBar();

Hope this helps!

For images and other sources you can use that:

$(el).one('load', function(){
// completed
}).each(function() {
if (this.complete)
$(this).load();
});

I came across the same problem and have found a simple solution. Add after calling the append function a document ready.

$("#root").append(child);
$(document).ready(function () {
// Action after append is completly done
});

Using MutationObserver can act like a callback for the jQuery append method:

I've explained it in another question, and this time I will only give example for modern browsers:

// Somewhere in your app:
var observeDOM = (() => {
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;


return function(obj, callback){
if( MutationObserver ){
// define a new observer
var obs = new MutationObserver(function(mutations, observer){
if( mutations[0].addedNodes.length || mutations[0].removedNodes.length )
callback(mutations);
});
// have the observer observe foo for changes in children
obs.observe( obj, { childList:true, subtree:true });


return obs;
}
}
})();


//////////////////
// Your code:


// setup the DOM observer (on the appended content's parent) before appending anything
observeDOM( document.body, ()=>{
// something was added/removed
}).disconnect(); // don't listen to any more changes


// append something
$('body').append('<p>foo</p>');

Although Marcus Ekwall is absolutely right about the synchronicity of append, I have also found that in odd situations sometimes the DOM isn't completely rendered by the browser when the next line of code runs.

In this scenario then shadowdiver solutions is along the correct lines - with using .ready - however it is a lot tidier to chain the call to your original append.

$('#root')
.append(html)
.ready(function () {
// enter code here
});

I'm surprised at all the answers here...

Try this:

window.setTimeout(function() { /* your stuff */ }, 0);

Note the 0 timeout. It's not an arbitrary number... as I understand (though my understanding might be a bit shaky), there's two javascript event queues - one for macro events and one for micro events. The "larger" scoped queue holds tasks that update the UI (and DOM), while the micro queue performs quick-task type operations.

Also realize that setting a timeout doesn't guarantee that the code performs exactly at that specified value. What this does is essentially puts the function into the higher queue (the one that handles the UI/DOM), and does not run it before the specified time.

This means that setting a timeout of 0 puts it into the UI/DOM-portion of javascript's event queue, to be run at the next possible chance.

This means that the DOM gets updated with all previous queue items (such as inserted via $.append(...);, and when your code runs, the DOM is fully available.

(p.s. - I learned this from Secrects of the JavaScript Ninja - an excellent book: https://www.manning.com/books/secrets-of-the-javascript-ninja )

Cleanest way is to do it step by step. Use an each funciton to itterate through each element. As soon as that element is appended, pass it to a subsequent function to process that element.

    function processAppended(el){
//process appended element
}


var remove = '<a href="#">remove</a>' ;
$('li').each(function(){
$(this).append(remove);
processAppended(this);
});​