【问题标题】:jQuery element exists eventjQuery 元素存在事件
【发布时间】:2011-11-05 09:29:22
【问题描述】:

一旦页面上存在特定元素,是否有用于调用回调的事件或简单函数。 我不是在问如何检查元素是否存在。

举个例子

$("#item").exists(function(){ });

我最终使用了 ready 事件

 $("#item").ready(function(){ });

【问题讨论】:

  • ready 函数似乎不能以这种方式工作@Drake。以这个小提琴为例:jsfiddle.net/YDn5f

标签: jquery events exists


【解决方案1】:

我也遇到了同样的问题,所以我继续为它写了一个插件:https://gist.github.com/4200601

$(selector).waitUntilExists(function);

代码:

(function ($) {

/**
* @function
* @property {object} jQuery plugin which runs handler function once specified element is inserted into the DOM
* @param {function} handler A function to execute at the time when the element is inserted
* @param {bool} shouldRunHandlerOnce Optional: if true, handler is unbound after its first invocation
* @example $(selector).waitUntilExists(function);
*/

$.fn.waitUntilExists    = function (handler, shouldRunHandlerOnce, isChild) {
    var found       = 'found';
    var $this       = $(this.selector);
    var $elements   = $this.not(function () { return $(this).data(found); }).each(handler).data(found, true);

    if (!isChild)
    {
        (window.waitUntilExists_Intervals = window.waitUntilExists_Intervals || {})[this.selector] =
            window.setInterval(function () { $this.waitUntilExists(handler, shouldRunHandlerOnce, true); }, 500)
        ;
    }
    else if (shouldRunHandlerOnce && $elements.length)
    {
        window.clearInterval(window.waitUntilExists_Intervals[this.selector]);
    }

    return $this;
}

}(jQuery));

【讨论】:

    【解决方案2】:

    LiveQuery jQuery 插件似乎是大多数人用来解决此问题的工具。

    Live Query 通过绑定事件或 自动触发匹配元素的回调,即使在 页面已加载并且 DOM 已更新。

    这是我整理的一个快速 jsfiddle 来演示这一点:http://jsfiddle.net/87WZ3/1/

    这是一个每次创建 div 时触发事件并写出刚刚创建的 div 的唯一 ID 的演示:http://jsfiddle.net/87WZ3/2/

    【讨论】:

      【解决方案3】:

      看看 .live 函数。它在选择器中的所有当前和未来元素上执行。

      $('div').live(function() {});

      【讨论】:

        猜你喜欢
        • 2013-03-10
        • 2011-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-28
        • 2012-04-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多