简体   繁体   中英

How to change html class after ajax successful response?

I want to toggle the voting arrow class, the same way as stackoverflow's voting arrow. For a logged in user, if already voted up, the html is:

<a href="#vote" id="vote-up-%1$d" class="vote vote-up-on"></a>
<a href="#vote" id="vote-down-%1$d" class="vote vote-down-off"></a>

After user clicked down arrow, if response success, How to change "vote-up-on" to "vote-up-off", and change "vote-down-off" to "vote-down-one"?

Well, this works the same as the SA votes - it could be a bit more concise but I really need to get back to work ;-)

<a href="#vote" id="vote-up-%1$d" class="vote vote-up">vote up</a>
<span class="votes">0</span>
<a href="#vote" id="vote-down-%1$d" class="vote vote-down">vote down</a> 

and the jquery:

$(document).on('click', '.vote-up', function () {
    if(!$(this).hasClass('vote-locked')){     
        var votes = parseInt($(this).parent().find('.votes').text());  
        if(!$(this).hasClass('vote-off')){

            $(this).addClass('vote-off');
            $(this).nextAll('a').addClass('vote-locked');
            votes++;

        }
        else{

            $(this).removeClass('vote-off');
            $(this).nextAll('a').removeClass('vote-locked');
            votes--;

        }
       $(this).parent().find('.votes').text(votes);
   }
 });

 $(document).on('click', '.vote-down', function () {
     if(!$(this).hasClass('vote-locked')){  
        var votes = parseInt($(this).parent().find('.votes').text());  
        if(!$(this).hasClass('vote-off')){

            $(this).addClass('vote-off');
            $(this).prevAll('a').addClass('vote-locked');
            votes--;

        }
        else{

            $(this).removeClass('vote-off');
            $(this).prevAll('a').removeClass('vote-locked');
            votes++;

        }
       $(this).parent().find('.votes').text(votes);
    }
 });

http://jsfiddle.net/gqDgL/

jQuery can add and remove classes, using addClass and removeClass,

$('#vote-up-%1$d').removeClass('vote-up-on');

$('#vote-up-%1$d').addClass('vote-up-off');
 $("#vote-up").click(function () {
            $(this).toggle();
            $(this).toggleClass("vote vote-down-off");
        });

try this

Make a callback function when you receive Ajax response.

function addVoteUpClass() {
    if (jQuery(".vote").hasClass("vote-up-on")) {
        jQuery(".vote-up-on").removeClass("vote-up-on").addClass("vote-up-off");
    }
}

jQuery.ajax({
    url: "your_url",
    method: "GET",
    success: function(data) {
        addVoteUpClass();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM