I am working within a site framework that I cannot modify. This framework adds a textbox to the DOM at some point after document.ready(). I want to give this textbox focus.
jQuery's live
, delegate
and on
are inappropriate because they require an event as a trigger. I could not find an event equivalent to just adding the item to the page.
There is LiveQuery, but the framework does not allow me to load it.
Is there a way to simulate LiveQuery or a better alternative that somebody can think of? I would love to be able to do:
http://jsfiddle.net/psJmx/1/
$(document).ready(function() {
//create an input in the future
setTimeout('insertInput()', 1200);
//give that input focus when it is added
$('#foo').live('load', function() {
$(this).focus();
});
});
function insertInput(开发者_StackOverflow中文版) {
$('body').append('<input type="text" value="new" id="foo" />');
}
Here's a new jsfiddle for you... Is that what you mean? http://jsfiddle.net/QsbU4/3/ I just altered your insertInput function. You no longer need the live
part.
As a note, I know that polling is a crappy way to do this, but I have constraints to work within. I have no control over the js that inserts the element and I can only use jQuery 1.4.2.
I ended up relying on polling. This is how I chose to do it. I gave a max number of attempts and a reasonable poll time so that I am not bogging down the page. If the element doesn't appear in the first three seconds I give up.
//poll for appearance of element
var attempts = 10;
var pollTime = 300;
modifyTree();
function modifyTree() {
if ($('#foo').length > 0) {
//do something to foo
}
else {
//continue polling for element
if (attempts--) { setTimeout('modifyTree()', pollTime);} }
}
精彩评论