3

我想在我的论坛上显示直接链接之前创建一个显示内容的链接。

  1. 显示下载附件的链接
  2. 点击后显示html内容,下方有5秒倒计时
  3. 倒计时结束后,会显示直接链接。

我尝试了以下代码:

$("button").click(function() { 
  $(function() {
    var count = 10; 
    countdown = setInterval(function() { 
      $("p.countdown").html(count + " seconds remaining!").show("slow"); 

      if (count == 0) { 
        $("p.new").show("slow");
      } 

      count--; 
    }, 1000);
  });
});
4

4 回答 4

2

魔法功能呢?

要谈论@Bradley Foster 的回答,多次调用setTimeout是不可靠的。setTimeout如果您的浏览器滞后,它将停止,因此有四种不同的顺序,您不确定顺序是否正确。setTimeout正如我展示的那样嵌套更好。

$('#button').click(function() {
    var seconds = 5, // Declare some variables for reuse
        el = $('#some_link')
    el.text(seconds) // Put it a five!
    // Name your function so that you can call it later
    setTimeout(function countdown() {
        // Your countdown is already at 5, so decrement it
        // Remember that you've already waited for 1000ms before reaching this line the first time
        seconds--
        el.text(seconds) // Set the new time left
        // If the countdown is not over, recall this function after 1000ms
        if (seconds > 0) {
            setTimeout(countdown, 1000)
        }
        // If it is over, display the link
        // Note that js will stop there and not try to call itself another time as it would with setInterval()
        else {
            el.html('<a href="link">Download</a>')
        }
    }, 1000)
})

顺便说一句,在你的问题中,当你在做的时候$(function() {...,你实际上在做$(document).ready(function() {...。我想这不是你想要的:)

Jsfiddle在这里:http: //jsfiddle.net/Ralt/kTbcm/

于 2012-04-04T12:16:58.207 回答
1

你可以这样做:

HTML:

<button>Download</button>

<p class="countdown" />
<p class="link">
    <a href="www.stackoverflow.com">StackOverflow</a>
</p>​

CSS:

p { display: none; padding: 50px; border: solid 1px black; }
p.countdown { color: red; font-size: 24px; }​

jQuery:

var $countdown = $("p.countdown"),
    $link = $("p.link"),
    $button = $("button");

$button.click(function() { 

    $countdown.hide(0);
    $link.hide(0);        

    var count = 10,
        countdown = setInterval(function() { 

           $countdown.html(count + " seconds remaining!").show("slow"); 

           if (count == 0) { 

               $countdown.hide(0);
               $link.show("slow");
               clearInterval(countdown);

           } 

           count--; 

       }, 1000);

});​
于 2012-04-04T12:33:02.097 回答
0

查看 jQuery 的showhide以及 JavaScript 的原生setTimeout

于 2012-04-04T10:59:33.860 回答
0
function countdownfunction() {
    $('#some_link').innerHTML = "5";
    $('#some_link').innerHTML = setTimeout("4",1000);
    $('#some_link').innerHTML = setTimeout("3",1000);
    $('#some_link').innerHTML = setTimeout("2",1000);
    $('#some_link').innerHTML = setTimeout("1",1000);

    $('#some_link').innerHTML = '<a href="newlink.php">download now</a>;
};

$('#some_link').click( countdownfunction() );
于 2012-04-04T10:59:35.610 回答