开发者

Keyword `this` problem with using in ajax function

ok this is some crazy jquery code that I have here. what its doing is going to a php file to get results of some sort and then slide down the results but if the results are already there just slide down

$('#compatibility h2').click(function(){
开发者_运维问答        var clicked = $(this);
        if($(this).hasClass('collapsed'))
        {
            $(clicked).removeClass('collapsed');
            if($($(this)[0].nextSibling).is('ul'))
            {
                $(this).next().slideToggle();
            }
            else
            {
            $.get("getproducts.php", {cid: $(this).attr('id'), did: $("#deviceId").val()},
                  function(data)
                  {   
                    $(clicked).after(data).next().slideToggle(); //adds a <ul> <li> </li> </ul>  
                  });
            }
        }
        else
        {

            $(this).addClass('collapsed');  
            $(this).next().slideToggle();
        }
        //$(this).css('margin','4px 0 7px');
});

now my question is kind of obscure but i was wondering why when I replace clicked with the keyword this the code does not insert the data after the h2 that was clicked. Also I am wondering if I am doing this in the best way with jquery.


Why are you doing this? var clicked = '#'+$(this).attr('id');?

This should work:

var clicked = $(this);


At first glance, I would think that using "this" would everywhere except inside your $.get(...). One trick that I use sometimes to get around callbacks and multiple versions of "this" is to add the following code at the top of my class or function:

var me = this;

Then I just use $(me) instead of $(this)


The problem is in line 10 or so where he says:

$(clicked).after(data).next().slideToggle(); //adds a <ul> <li> </li> </ul>  

If you replace clicked with this there, it will stop working: this will be pointing to the response from the $.get not any DOM element.


Lines 2 and 3 look very wrong to me, if what you're doing is what I think you're doing then what you're doing is building a string '#' + id_of_clicked_element, and then trying to run jQuery operations on it. That's never going to work! And it's also unnecessary.

Just if ($(this).hasClass ('collapsed')) should do fine.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜