我的代码有问题.Chrome代码观众说第21行有问题,问题是:Uncaught TypeError: Object #<HTMLElement> 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('<li id="' + value.pk + '">' + value.fields.title + ' <span class="plus">+</span></li>');});
$('<ul/>', {
html: items.join('')
}).insertAfter(id); })
} else {(this).parent().next().children().show()} /* 2 ELSE */
} else {$(this).text('+').parent().next().hide()} /* 1 ELSE */
})
})
Run Code Online (Sandbox Code Playgroud)
我的HTML看起来像这样:
<ul>
<li id="3"><a href="/my/proper/url/">this is for eat</a>
<span class="plus">+</span></li> <!-- after clickin this I get proper json data, and "+" is cahnged to "-", and the next "<ul>" element appear -->
<ul>
<li id="4">fishes
<span class="plus">+</span></li>
</ul>
</ul>
Run Code Online (Sandbox Code Playgroud)
当我点击第一个"li"元素中的" - "然后再次点击"+"时,我得到:
Uncaught TypeError: Object #<HTMLElement> has no method 'parent'
Run Code Online (Sandbox Code Playgroud)
也许我错过了一些明显的东西,但我还没有进入jQuery.我要求对初学者有一些宽容,以及我在哪里可以搞错的任何想法.谢谢.
Jam*_*ice 16
在这一行:
} else {(this).parent().next().children().show()}
Run Code Online (Sandbox Code Playgroud)
您缺少$before (this),这意味着您正在尝试调用parent()DOM元素,而不是jQuery对象.