jQuery element exists event

早过忘川 提交于 2019-12-08 20:31:38

问题


Is there an event or simple function for a calling a callback once a specific element exists on the page. I am not asking how to check if an element exists.

as an example

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

I ended up using the ready event

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

回答1:


The LiveQuery jQuery plugin seems to be what most people are using to solve this problem.

Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.

Here's a quick jsfiddle that I put together to demonstrate this: http://jsfiddle.net/87WZ3/1/

Here's a demo of firing an event each time a div is created and writing out the unique id of the div that was just created: http://jsfiddle.net/87WZ3/2/




回答2:


I was having this same problem, so I went ahead and wrote a plugin for it: https://gist.github.com/4200601

$(selector).waitUntilExists(function);

Code:

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



回答3:


Take a look at the .live function. It executes on all current and future elements in the selector.

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



来源:https://stackoverflow.com/questions/7219795/jquery-element-exists-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!