Since .live() is deprecated, I started to use .on().
I have the following code:
$('.myClass').on("click", function(event)
{
var args = '......';
SendAjax(args);
});
The SendAjax function does this:
SendAjax(args)
{
$.ajax(
{
type: "POST",
url: webPageName,
data: queryParams+'&'+unique,
success: function(result)
{
MyReturnFunction(result);
}
});
}
The ajax will return to this function:
MyReturnFunction(response)
{
$('.myClass').html(response);
}
But after this MyReturnFunction(), the events on .myClass doesn’t work anymore. How do I fix this with .on() or .bind()?
The
.on()function can take an extra argument:That’s what
.live()did for you, but it was a backwards API design. Now you have to decide where to put the delegated handler. The body element is a good default, but it can be any parent. Sometimes when you’re handling clicks on things in tables it’s nice to do the binding at the<table>element (though the body works fine then too).So basically the rule is that when you used to write:
you write:
The “container-selector” says where you want the real event handler placed — the one that checks to see whether the target of a bubbled event matches the given “something” selector. As before, you can pass a list of event names (separated by spaces) instead of just one. There’s also a variant that lets you pass an object mapping event names to functions.