2012-08-10 58 views
0

jquery next()在我的代码中不工作。我的HTML代码jquery next()不工作

<a class="reply">Reply</a> 
<div class="respond" style="display:none;">respond 1</div>  
<a class="reply">Reply</a> 
<div class="respond" style="display:none;">respond 2</div> 
<a class="reply">Reply</a> < 
div class="respond" style="display:none;">respond 2</div> 

我jQuery代码是

$('.reply').click(function(e){ 
     e.preventDefault(); 
     $(this).next().show(); 
}); 

,但它无法正常工作。请给我一个解决方案

+3

这应该工作,你确定jQuery加载正确吗? _it是什么意思是不工作的? http://jsfiddle.net/d3VGz/ – undefined 2012-08-10 07:44:12

+0

我不明白什么问题,但在[小提琴](http://jsfiddle.net/t7jYp/)从你的代码一切正常。 – vadim 2012-08-10 07:47:03

+0

这工作正常http://jsfiddle.net/5Umjd/你检查如果jQuery加载? – 2012-08-10 07:47:14

回答

2

执行顺序很重要。如果您的jQuery代码位于HTML之前以定义元素,那么代码将在这些元素存在之前运行,因此不会绑定事件处理程序。在这些情况下,您需要使用jQuery .ready()函数为DOM就绪事件绑定事件处理程序,以便在绑定事件处理程序时保证元素存在。

$(document).ready(function() { 
    $('.reply').click(function(e){ 
     e.preventDefault(); 
     $(this).next().show(); 
    }); 
});