I'm making a simple AJAX call that it is getting trigger after someone clicks an anchor. After the AJAX is successful I would like to add a class at the anchor that triggered the AJAX.
Although the script is working fine, and the success function returns all the correct data, when I try to addClass()
it doesn't work. I used a hide()
method to see if jQuery runs correctly and it doesn't work either. The console doesn't print any errors.
For debugging I used an alert and it works! How can the alert work fine and both addClass()
and hide()
not?
<a href="#" class="refreshor" value="20">1</a>
<a href="#" class="refreshor" value="40">2</a>
jQuery(document).ready(function($) {
$('.refreshor').on('click',function(e){
e.preventDefault();
var search = $('#searchin').val();
var page = $(this).text();
var that = this;
$.ajax({
type: "POST",
url: "components/com_tagger/scripts/ajaxSearch.php",
data: {
"search": search,
"page": page
},
success:function(response) {
$('.ajaxSearchResults').html(response);
$(that).addClass('preventer'); //this doesnt work
$(that).hide(); //this doesnt work
var test = $(that).text();
alert(test); //this works!
}
});
});
});
Inside the success callback you replace the content of .ajaxSearchResults
$('.ajaxSearchResults').html(response);
Then that
is not referring to the ones that are inside this container.
You need to use delegate, that will allow you to bind events on elements that not yet in the DOM
$('.ajaxSearchResults').on('click', '.refreshor',function(e){
e.preventDefault();
var search = $('#searchin').val();
var page = $(this).text();
var thisValue = $(this).attr('value'); // save the current value of the `a` clicked
$.ajax({
type: "POST",
url: "components/com_tagger/scripts/ajaxSearch.php",
data: {
"search": search,
"page": page
},
success:function(response) {
$('.ajaxSearchResults').html(response);
var that = $('.ajaxSearchResults').find('.refreshor[value="'+thisValue+'"]');
// look for the `a` that have the saved value.
that.addClass('preventer');
that.hide();
var test = that.text();
alert(test);
}
});
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments