开发者

jquery check class problem,

I have a button that depending on a class value should send different values to the POST however what ever happens it is only running one condition, whatever I do I can only get it to send the POST the method=add data.

This is my code

$("a.navlink").click(function (ev) {
    $(this).removeClass("active");
    var url = $(this).attr("href")
    ev.preventDefault();
    if($('a.navlink:not(.active)')) {

        $.ajax ({
             url: url,
             type: "POST",
             data: "method=add",
             success : function (html) {
                $('#accordion').accordion('destroy');
                 $("#accordion").append(html);
                 $('#accordion').accordion({
                     active: 0,
                     header:'h2.Blog'
                 });
             //alert(accordion())
             }
         });
    }
    if ($(this).hasClass("active")) {
    //  $(this).addClass('active')
    $.ajax ({
         url: url,
         type: "POST",
         data: "method=delete",
         success : function (html) {
            alert("hello")
            $(this).removeCl开发者_如何学编程ass('active')
         //alert(accordion())
         }
     });    
    }


     });

Basically what I need is, if when the button is clicked it gets a class called active added to it and the ajax runs, when it is clicked again, the class needs to be removed and the ajax run, is this possible?


What you are basically doing now in your first if clause is that you're checking whether $('a.navlink:not(.active)') is true or false – $() always returns an object which evaluates to true.. You should do a hasClass on that also. And you are removing the 'active' class before the if, so how can you compare it later on?

It is unclear what you're trying to do, but what you want is probably something like this:

$("a.navlink").click(function(ev) {
    var url = $(this).attr("href")
    ev.preventDefault();
    // If the link is not active, run 'add':
    if(!$(this).hasClass('active')) {
        $.ajax ({
            url: url,
            type: "POST",
            data: "method=add",
            success: function (html) {
                $('#accordion').accordion('destroy');
                $("#accordion").append(html);
                $('#accordion').accordion({
                    active: 0,
                    header:'h2.Blog'
                });                
            }
        });
        // Mark it as active
        $(this).addClass('active');
    // If the link is active, run 'delete':
    } else {
        $.ajax ({
            url: url,
            type: "POST",
            data: "method=delete",
            success: function (html) {
                alert("hello")
            }
        });
        // Unmark it.
        $(this).removeClass('active');
    }        
});

That code's purpose doesn't make much sense to me, so tell me if I understood you wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜