Search code examples
jqueryfindchildren

jQuery $(this).find and $(this).children not working in this code? if right, tell me reason


<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
var commentUrl = 'comment.jsp';

$('.privateTimeline').click(function() {
 $.ajax({
 url: commentUrl,
 type:'post',
  data:{
       no : $(this).find('.no').text()  // working!
 },
 success:function(data){
    if( $(this).children('.comment').is(':hidden') ) {  // not working!
    $(this).find('.comment').slideDown(400);  // not working!
    $(this).find('.comment').html(data);   // not working!
 }
 else {
    $(this).find('.comment').slidUp(400);  // not working!
  }
 });
})

</script>
  1. I don't know well reason than this code is not working.
  2. I want to select privateTimeline's children class node so make event.
  3. not work in success function part but $(this) is working in data part.

Solution

  • This should work :

    var $target =$('.privateTimeline');
    $target.click(function() {
        $.ajax({
            url: commentUrl,
            type:'post',
            data:{
                no : $(this).find('.no').text()  // working!
            },
            success:function(data){
               if( $target.children('.comment').is(':hidden') ) {  // not working!
                   $target.find('.comment').slideDown(400);  // not working!
                   $target.find('.comment').html(data);   // not working!
                }
                else {
                    $target.find('.comment').slidUp(400);  // not working!
                 }
            }
        });
    });
    

    In success:function(data){}, $(this) doesnt point to $('.privateTimeline') anymore. So you access it using its unique selector.

    Also, you had your closing brackets wrong, so I corrected that for you.