jQuery - 返回按钮或等待你自动重定向 - 高级返回按钮

Dra*_*zek 2 javascript jquery

我用这个按钮了一会儿:

<input type="button" class="button" onclick="javascript:history.go(-1)" value="Go back to previus page" />
Run Code Online (Sandbox Code Playgroud)

我想添加功能,但我不知道,因为即时通讯新闻,所以请给我一些提示甚至解决方案.

我希望你能从这个按钮所在的页面重定向,自动在10秒钟内(timmer应显示在实际按钮上).或者如果你点击你会立即重定向?

任何想法如何用jquery做到这一点?

Jef*_*f B 7

不需要jQuery.把它放在你的标题中.它将history.go(-1)在10000毫秒或10秒后调用.

<script type="text/javascript">
      setTimeout( function() {
           history.go(-1);
      }), 10000);
</script>
Run Code Online (Sandbox Code Playgroud)

我刚注意到你想在按钮上安装一个计时器.这可以使用一点点jQuery.当你在它时,你应该将你的内联javascript移动onclick="javascript:..."到你的脚本体.内联javascript已经失宠,主要是因为它是一种糟糕的做事方式.

<script type="text/javascript">
      $( function() {
             // While you are at it, remove do the click handler here:
             $(document).on('click', '.button', function() {
                 history.go(-1);
             })

             // Get button name, init timer value
             var buttonName = $('.button').val();
             var time = 10;

             function updateButton() {
                  // Set button name to "Go back to previus page (X)"
                  $('.button').val(buttonName+' ('+time+')');

                  if(time <= 0) {
                       // If we reached 0, redirect
                       history.go(-1);
                  } else {
                       //decrement time counter  
                       time--;
                       // otherwise, wait a second and do it again
                       setTimeout(updateButton, 1000);
                  }
             }

             // Start the counter
             updateButton();
      });
</script>
Run Code Online (Sandbox Code Playgroud)

你也可以使用setInterval(),但这让你在时间0设置按钮计时器更容易一些.

示例:http://jsfiddle.net/jtbowden/gJsPw/