Will this kind of code always work?
$('#container').append('<div id="theonly">tests</div>').find('#theo开发者_如何学运维nly');
and
$('#container').html('<div id="theonly">tests</div>').find('#theonly');
I'm worried sometimes the dynamically generated elements is not available at once,am I wrong or not?
If I'm not wrong,what's the solution to cover all cases?
EDIT Can someone come up with a definite and unified answer?
In the world of DOM, anyone who answers this question with "yes" is insane.
The html(val)
function replaces innerHTML
directly, so in theory this code should always work, since #container
will in fact have the new html code by the time you call find()
However, DOM is notorious for behaving differently across different browsers. So the lesson here is to test thoroughly.
EDIT: In response to "what is your solution?"
As I said above, you should thoroughly test. The function should work as expected, but you can never be sure without testing the major browsers.
With that said, if you really want a concrete confirmation that the new HTML is ready for querying, you can set up a poll that checks the current html()
against the html you want to set in the first place.
Something like this:
(function ($) {
$.fn.htmlX = function (html, callback) {
var element = this;
var poll = function () {
if (element.html() === html) {
callback();
} else {
setTimeout(poll, 100);
}
};
element.html(html);
poll();
};
$('#container').htmlX('<div id="theonly">tests</div>', function() { $('#container').find('#theonly').css('color', '#f00'); });
}(jQuery));
精彩评论