【问题标题】:Using jquery to toggle between different function and not getting resumed where it left使用 jquery 在不同的功能之间切换,而不是在离开的地方恢复
【发布时间】:2009-05-29 07:17:23
【问题描述】:

第一个函数的代码在特定的间隔 5 秒 (div1,div2,div3) 上显示三个不同的 div。
用于停止显示 div 的第二个函数的代码。

在显示 div2 时,我单击了链接以停止在该点停止。
但在那之后我再次单击它并显示 div1 (它的切换很好)但我想继续下一个显示 div3 的操作.

Jquery 代码:

$(function() {

 var IntervalId;

 function first_function() {
 var counter = 0,
 divs = $('#div1,#div2,#div3');
 function showDiv () {
           divs.hide() // hide all divs
          .filter(function (index) { return index == counter % 3; }) 
          .show('fast'); // and show it
          counter++;
 }; 
 showDiv();     
 IntervalId = setInterval(showDiv, 5000);
 }; 

 function second_function(){  
  clearInterval(IntervalId); 
 }  

 $("#link1").toggle(
 first_function,second_function
 );

});

HTML 代码:

<a href="javascript:void(0);" id="link1">Toggle</a>

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    将 counter 的初始化移到 first_function() 之外:

    $(function() {
    
     var IntervalId;
     var counter = 0,
    
     function first_function() {
     divs = $('#div1,#div2,#div3');
     ...
    

    在您的示例中,每次调用 first_function() 时,计数器都会设置回零。

    【讨论】:

      【解决方案2】:

      玩得开心:

      <script type="text/javascript">
      $(function() {
        var divFunctions = [];
        var $divs = $('#div1,#div2,#div3');
      
        $divs.each(function() {
          var $this = $(this);
          divFunctions.push(function() {
            return function() {
              $divs.not($this).hide();
              $this.show("fast")
            };
          }());
        });
      
        var $toggle_button = $("#link1");
        $toggle_button.toggle.apply($toggle_button, divFunctions);
      });
      </script>
      
      <body>
        <a href="javascript:void(0);" id="link1">Toggle</a>
      
        <div id='div1' style="display:none;">content1</div>
        <div id='div2' style="display:none;">content2</div>
        <div id='div3' style="display:none;">content3</div>
      </body>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-13
        • 1970-01-01
        • 2012-05-16
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多