如何模仿jQuery插件LiveQuery? [英] How to mimic the jQuery plugin LiveQuery?

查看:63
本文介绍了如何模仿jQuery插件LiveQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在无法修改的网站框架内工作.该框架在document.ready()之后的某个时刻向DOM添加了一个文本框.我想把重点放在这个文本框上.

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的livedelegateon不合适,因为它们需要一个事件作为触发器.我找不到一个等同于仅将项目添加到页面的事件.

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.

有LiveQuery,但是该框架不允许我加载它.

There is LiveQuery, but the framework does not allow me to load it.

有没有一种方法可以模拟LiveQuery或有人可以想到的更好的替代方法?我希望能够做到:

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" />');
}

推荐答案

请注意,我知道轮询是执行此操作的一种卑鄙的方法,但是我有一些工作上的限制.我无法控制插入元素的js,只能使用jQuery 1.4.2.

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);} }
}

这篇关于如何模仿jQuery插件LiveQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆