开发者

jQuery: live function for initializing plugins

i've made some little widget-plugin开发者_开发知识库s which are getting applied to eg. a textbox like $("input.txtbox").myTextbox();

now i'm using ajax for dynamically loading content and i was wondering: is there a way to use jquery's live function for auto-applying that plugin to each textbox which will be loaded via ajax?

thanks


You can't use .live() but you can set up a global ajaxSuccess or ajaxComplete handler.

$.ajaxSuccess(function ()
{
    $('input.txtbox').myTextbox();
});

You might want to make this more efficient by not re-initializing the plugin on inputs which already have been initialized; something like

$.ajaxSuccess(function ()
{
    $('input.txtbox:not(.myTextbox)').myTextbox().addClass('myTextbox');
});


There are actually events triggered when the DOM structure is modified. Whenever a new textbox is created and inserted into the document, you could react to bind your plugin initialization code. The events in question for you purpose are DOMNodeInserted (node was added a a child node to another element) and DOMNodeInsertedIntoDocument (node was initially inserted into document).

Note that availability of these events is not guaranteed / event is not supported by all browsers. Thus you'd need to check this with your targeted browsers / implementations and probably use Matt's approach to have it working across browsers.

Assuming your targeted browsers support the events, you'd do something similar to:

$(document).live('DOMNodeInserted', function(e){
    // Get inserted node from event and initialize your plugin if the element is initially seen
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜