admin管理员组

文章数量:1356815

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: "ponents/_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!                  
            } 
        });
    });
});

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: "ponents/_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!                  
            } 
        });
    });
});
Share Improve this question edited Dec 23, 2015 at 10:34 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Dec 23, 2015 at 10:31 sinsin 351 silver badge4 bronze badges 4
  • 2 are the links inside .ajaxSearchResults ? – Hacketo Commented Dec 23, 2015 at 10:34
  • yes they are inside – sin Commented Dec 23, 2015 at 10:37
  • 3 @sin, so the link bound to that is not part of the DOM anymore by the time you addClass() and hide() it. It was replaced by another link from the markup in the response. – Frédéric Hamidi Commented Dec 23, 2015 at 10:38
  • 1 So the clicked link is overwritten with response? – BenG Commented Dec 23, 2015 at 10:39
Add a ment  | 

5 Answers 5

Reset to default 4

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: "ponents/_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);        
        } 
    });
});

You have stated (in ments) that the links you have (for which you're trying to add a class) a reference for are inside the panel where you are replacing the entire content.

By replacing the content, the reference you have to the links are no longer in the DOM. You will need to have some way of identifying which link was pressed, and find that link again in the replaced markup.

One suggestion would be to identify the links using data-* attributes (value is not a valid property of an a element)

<a href="#" class="refreshor" data-value="20">1</a>
<a href="#" class="refreshor" data-value="40">2</a>

And on click capture that value:

$('.refreshor').on('click',function(e){
    e.preventDefault();
    var search = $('#searchin').val();
    var page = $(this).text();
    var val = $(this).data('value');
    ....

When you replace the content, you could then find this link:

success:function(response) {
     $('.ajaxSearchResults').html(response);
     $('.refreshor').filter(function(){
        return $(this).data('value') == val;
     }).addClass('preventor');
     ...

If you are replacing the anchors and you want to set the same one later, save its value to a variable and look it up after you replace it all in the success:-

Note a does not have a value so use data-value="20" instead.

html

<a href="#" class="refreshor" data-value="20">1</a>
<a href="#" class="refreshor" data-value="40">2</a>

js

jQuery(document).ready(function($) {
    $(document).on('click', '.refreshor', function(e){
        e.preventDefault();
        var search = $('#searchin').val();
        var page = $(this).text();
        var that = this;
        var value = $(this).data('value');
        $.ajax({    
            type: "POST",
            url: "ponents/_tagger/scripts/ajaxSearch.php",
            data: {
                "search": search,
                "page": page
            },
            success:function(response) {
                $('.ajaxSearchResults').html(response);

                $('.refreshor[data-value="' + value + '"]').addClass('preventer');
                $('.refreshor[data-value="' + value + '"]').hide();

                var test = $(that).text(); 
                alert(test); //this works!                  
            } 
        });
    });
});

UPDATE

And use event delegation to bind the click so the event is not lost.

Based on your ments and answers i came up to this that works fine:

I added id attributes to anchors

  <a href="#" id="link1" class="refreshor" >1</a>
  <a href="#" id="link2" class="refreshor" >2</a>

And changed the js to this:

jQuery(document).ready(function($) {

    $('.refreshor').on('click',function(e){
        e.preventDefault();
        var search = $('#searchin').val();
        var page = $(this).text();
        var that = '#link'+ page;

        $.ajax({

            type: "POST",
            url: "ponents/_tagger/scripts/ajaxSearch.php",
            data: {"search":search,"page":page},
            success:function(response) {
                $('.ajaxSearchResults').html(response);
                $(that).addClass('preventer');


            } 
        });


    });

});

You have to add it after ajax triggers.

<a href="#" class="refreshor" value="20">1</a>
<a href="#" class="refreshor" value="40">2</a>




jQuery(document).ready(function($) {
  $(document).on('click', '.refreshor', function(e){
     e.preventDefault();
     var search = $('#searchin').val();
     var page = $(this).text();
     var that = this;
     $.ajax({    
        type: "POST",
        url: "ponents/_tagger/scripts/ajaxSearch.php",
        data: {
            "search": search,
            "page": page
     },
     success:function(response) {
       $('.ajaxSearchResults').html(response);
       $(that).hide(); //this doesnt work
       var test = $(that).text(); 
       alert(test); //this works!                  
     }

     $(that).addClass('preventer'); //check it out

   });
 });
});

本文标签: javascriptaddClass() function doesn39t work after ajax callStack Overflow