jQuery元素存在事件

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

举个例子

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

我最终使用了ready事件

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

LiveQuery jQuery插件似乎是大多数人用来解决这个问题的。

Live Query利用jQuery选择器的强大function,通过绑定事件或自动神奇地触发匹配元素的回调,即使在页面加载和DOM更新后也是如此。

这是一个快速的小说,我把它放在一起来certificate这一点: http : //jsfiddle.net/87WZ3/1/

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

我遇到了同样的问题,所以我继续为它写了一个插件: 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)); 

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

$(’div’)。live(function(){});