I have a basic toggle function, when item is clicked initially it sends an ajax post, and when clicked the second time it sends a second different ajax post.
the issue is once it makes the ajax call, the second toggle function no longer fires.
When I removed the ajax functions from the toggle and replaced them with a basic show/hide div, it worked just fine first and second click.
Below is my code:
You will notice I have a basic show/hide function for the first click, for testing purposes. Using this code the first click works, second click works and make the ajax call, but any clicks after dont do anything.
//Sort by Instrument ACS or DESC
$("th#seeking").toggle(function()
{ // first click update sorting order
$("a.add_listing").hide(200);
$("a.add_listing").show(200);
},
function()
{ // On second Click togg开发者_开发百科le opposite sorting order
$.ajax({
type: "POST",
url: "ajax_calls.php",
data: "order=instrument_asc&sort_item=true",
success: function(r){$("#listings").html(r);},
error: function(){alert(2);$("#error").text("Could not retrieve posts").fadeIn(300).delay(900).fadeOut(300)}
})
});
Any help on this would be very much appreciated. Many thanks
If the portion of the page containing the element that's clicked is replaced by the AJAX results, then the handler will be lost. You could do something like this instead:
$(function() {
var toggleState = 0;
$('body').delegate('th#seeking', 'click', function() {
if (toggleState === 0) {
$("a.add_listing").hide(200);
$("a.add_listing").show(200);
}
else {
$.ajax({
type: "POST",
url: "ajax_calls.php",
data: "order=instrument_asc&sort_item=true",
success: function(r){$("#listings").html(r);},
error: function(){
alert(2);
$("#error").text("Could not retrieve posts")
.fadeIn(300).delay(900).fadeOut(300)
}
});
}
toggleState = toggleState ^ 1;
});
});
That sets up a "click" handler and keeps track of the toggle state explicitly, but it makes the handler work on the event as it bubbles up to the <body>
(you could put the handler at a closer container in the DOM if you wanted to). Thus even if you replace the page fragment, as long as the new fragment has that "id" value on the table header, the delegated event handler will "see" it.
edit — I changed that slightly to indicate that this should be done in a "ready" handler, or in some other way such that the <body>
element exists in the DOM. If the code were to run in a <script>
block in the <head>
without being set up as a "ready" or "load" handler, then the <body>
won't be there and it won't do anything.
edit again — Here is a faked-up demo. There was a big in my code above (missing "})" towards the end) that I've fixed in that fiddle, and that I'll fix here too.
I would have thought using jquery.live() would be a good solution, like the answer seen here: Using jQuery .live with toggle event
精彩评论