开发者

How to Apply jQuery to Elements Not Available at Document.Ready?

The website I am developing uses jQuery UI tabs to load content via AJAX (in this case, each tab is made up of a partial page). This works well, and I am happy with those results. However, one problem I have repeatedly come across is that when I include jQuery within my master.js file (which I use for site-wide Javascript), it DOES NOT apply to anything that is loaded in via AJAX. For example, I tried something simple like:

// Theme all the buttons with jQuery UI themes.
$('input:button').button();

However, all the buttons on the tabs are not themed appropriately.

How do I fix this? I was thinking something with jQuery's .live() function, but b开发者_如何转开发oth the 'load' and the 'ready' events don't appear to be working. This has become a pretty frustrating problem so any help that can be provided would be most appreciated.


Well, the livequery plugin ( http://docs.jquery.com/Plugins/livequery ) used to be used for a lot of stuff like this. It's not the most efficient way to handle the problem, though.

If you're adding content via AJAX, why not just re-assign handlers for the content after you add it?

// setup simple jQuery plugin to handle all of your custom logic (although this could be a normal function as well)
$.fn.assignMyHandlers = function(){
    return this.each(function(){
        $(this).find('input:button').button();
        // etc
    });
};

// and then everywhere that you bring in AJAX'd content...
$.get('test.html', function( html ) {
    var $fragment = $( html );
    $fragment.assignMyHandlers();
    $fragment.appendTo( "#theList" );
});


You can apply it to those new elements in your AJAX callback:

$.ajax({
    url:'/some/path',
    success: function( resp ) {
        var $newElements = $(resp);  //create jQuery object of new elements
        $newElements.find('input:button').button();  // call .button() on inputs
        $newElements.appendTo('body');  // append to wherever
    }
});

I have no idea what is happening in your AJAX callback, but this should give you the general idea.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜