简体   繁体   中英

How to mimic the jQuery plugin LiveQuery?

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() {
    $('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);} }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM