2013-10-28 33 views
0

我不明白为什么jQuery脚本不工作。 下面是示例:JQUERY slidetoggle无法正常工作

$(document).ready(function(){ 
     $('#mygtukas-js').click(function(){ 
     $(this).data('clicked', true); 
     }); 

     if($('#mygtukas-js').data('clicked')){ 
     $(this).next('#turinys').slideToggle(500); 
     } 
     else { 
     $('#turinys').hide(); 
     } 
    }); 

的jsfiddle:http://jsfiddle.net/5NmK9/

+0

你是什么意思与“不工作”? – melancia

+0

我的div不滑动。 :( –

+1

你可以将完整的代码发布到jsfiddle.net并重现该错误吗? – Latheesan

回答

1

你的slideToggle块被调用一次,上的document.ready。当你点击#mygtukas-js时,它会将'clicked'改为true,但它不会调用if/else块。

您应该将if/else块放在单击后调用的代码中,或者将它放在其自己的事件侦听器中。

1

这应该是足够了:

$(document).ready(function(){ 
    $('#mygtukas-js').on("click", function() { 
     // The line below can be removed if you're not using the data 
     // value anywhere else. 
     $(this).data('clicked', true); 

     $(this).next('#turinys').slideToggle(500); 
    }); 
}); 

.slideToggle()会做的显示/隐藏。

演示:http://jsfiddle.net/5NmK9/1/

+0

我想补充说,除非它在其他地方使用,否则它可能是有意义的,一个简单的slideToggle将跟踪状态。 –

+0

@MikeManfrin正好。 – melancia