jQuery – 未捕获TypeError:对象#没有方法’parent’

我的代码有问题。 Chrome代码观众说第21行有问题,问题是这样的: Uncaught TypeError: Object # has no method 'parent' 。 这是jQuery代码:

  $('.plus').click(function(){ if ($(this).text() == "+"){ /* 1 IF */ $(this).text("-"); if (! ($(this).parent().next().is('ul'))){ /* 2 IF */ var element_id = $(this).parent().attr('id') var id = '#' + element_id var url = "/accounts/profile/thingh_update/" + element_id + "/"; $.getJSON(url, function(data){ var items = [] $.each(data, function(index, value) { if(value.pk) items.push('
  • ' + value.fields.title + '  +
  • ');}); $('
      ', { html: items.join('') }).insertAfter(id); }) } else {(this).parent().next().children().show()} /* 2 ELSE */ } else {$(this).text('+').parent().next().hide()} /* 1 ELSE */ }) })

    我的HTML看起来像这样:

     
    • this is for eat   +
    • <!-- after clickin this I get proper json data, and "+" is cahnged to "-", and the next "
        " element appear -->
        • fishes   +

    当我点击第一个“li”元素中的“ – ”然后再次点击“+”时,我得到:

     Uncaught TypeError: Object # has no method 'parent' 

    也许我错过了一些明显的东西,但我还没有进入jQuery。 我要求对初学者有一些宽容,以及我在哪里可以搞错的任何想法。 谢谢。

    在这一行:

     } else {(this).parent().next().children().show()} 

    你错过了$ before (this) ,这意味着你试图在DOM元素而不是jQuery对象上调用parent()

     } else {(this).parent().next().children().show()} 

    你之前忘记了$ (this) 。 它应该是:

     } else {$(this).parent().next().children().show()}