JQuery UI Tabs - rebinding events for tabs loaded via ajax
Is there a proper way to rebind events in JQuery UI when tabs are loaded via ajax. For example, in the code below, I have the success event call an 'initBinding()' function which sets up some custom click event handlers for different classes. The problem with this is, when I switch tabs a bunch of times, then fire off one of the click events, I get some weird screen flicker effects. If I refresh the entire page, then go directly to the click event, it doesn't flicker. So I think it has something to do with it binding multiple times.
If I take the 'initBinding()' method out of the success event, any tab that gets loaded via ajax will not trigger any of the events I have setup. Is there a standard/better way to do handling binding events like this?
$(document).ready(function () {
$("#tabs").tabs({
select: function (event, u开发者_StackOverflow中文版i) {
var tabID = "#ui-tabs-" + (ui.index + 1);
$(tabID).html("<b>Fetching Data....Please wait....</b>");
},
ajaxOptions: {
error: function (xhr, status, index, anchor) {
$(anchor.hash).html("Could not load tab data");
},
success: function (xhr, status, index, anchor) {
initBinding();
}
}
});
});
function initBinding() {
$(".editButton").click(function () {
//event logic...
});
}
You should use jQuery's .live() to
Attach a handler to the event for all elements which match the current selector, now and in the future.
In your code:
$(".editButton").click(function () {
will become
$(".editButton").live('click', function () {
Using this technique, you can remove the initBinding()
function altogether, and use the .live()
statement in the onready function.
精彩评论