jquery + ajax替换类

时间:2015-10-30 21:13:19

标签: jquery ajax

我尝试用ajax替换按钮类,我做错了什么?

我的按钮:

<input type="button" class="btn btn-default btn-sm addLike" name="{{ answer.pk }}" value="Like" ></input>

我的js:

$('.addLike').click(function(){

    $.ajax({
        type: "POST",
        url: "{% url 'add_like' %}",
        data: {'answer_pk': $(this).attr('name'), 
                'csrfmiddlewaretoken': '{{ csrf_token }}'},
        dataType: 'json',
        success: function(response){
            alert(response.message);
            if ( $(this).hasClass('btn-default')) {
                $(this).removeClass('btn-default').addClass('btn-success');
            }
            else if ($(this).hasClass('btn-success')) {
                $(this).removeClass('btn-success').addClass('btn-default');
                }

            }
    }); 
})

消息,它只是来自我的django视图功能的测试警报消息。只有替换元素的问题

2 个答案:

答案 0 :(得分:3)

Inside the callback, $(this) refers to the jqXHR object of the Ajax call, not the element the event handler was bound to.

try doing this.

$('.addLike').click(function() {

    var element = this; // adding the current object in a variable

    $.ajax({
        type: "POST",
        url: "{% url 'add_like' %}",
        data: {
            'answer_pk': $(element).attr('name'),
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        },
        dataType: 'json',
        success: function(response) {
            alert(response.message);
            if ($(element).hasClass('btn-default')) {
                $(element).removeClass('btn-default').addClass('btn-success');
            } else if ($(element).hasClass('btn-success')) {
                $(element).removeClass('btn-success').addClass('btn-default');
            }
        }
    });
});

hope it helps.

答案 1 :(得分:1)

A simple toggleClass would do the job, without checking for individual classes and adding and removing them.

$("input").click(function()
{
    $(this).toggleClass('btn-default btn-success');
    alert($(this).attr("class"));
});

http://jsfiddle.net/vwLfxdya/