问题
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