在document.write中使用javascript延迟

时间:2012-10-12 09:30:47

标签: javascript function delay

有人可以帮我输入这段代码的javascript延迟吗? 我想让这段代码在2秒后打开。当你打开网址。 其余的网站负载正常。

<script type="text/javascript">

var avail=$z:value[article.availableinstock];

if ($z:value[article.availableinstock] < 1)
{
document.write('<div class="shop_not">');
document.write("In order!");
}
else if ($z:value[article.availableinstock] >=100)
{
document.write('<div class="shop_ok">');
document.write(" 100+ in stock" );
}
else if ($z:value[article.availableinstock] >=50 )
{
document.write('<div class="shop_ok">');
document.write(" 50+ in stock" );
}
else if ($z:value[article.availableinstock] >=25 )
{
document.write('<div class="shop_ok">');
document.write(" 25+ in stock" );
}
else
{
document.write('<div class="shop_bob">');
document.write(+ avail.toFixed(0));
document.write(" in stock" );
}
</script>

2 个答案:

答案 0 :(得分:1)

解决方案是将所有内容放入setTimeout(function() {... your stuff ...}, 2000)来电。

这应该是:

function yourStuff() {
  var avail=$z:value[article.availableinstock];

  if ($z:value[article.availableinstock] < 1) {
    document.write('<div class="shop_not">');
    document.write("In order!");
  } else if ($z:value[article.availableinstock] >=100) {
    document.write('<div class="shop_ok">');
    document.write(" 100+ in stock" );
  } else if ($z:value[article.availableinstock] >=50 ) {
    document.write('<div class="shop_ok">');
    document.write(" 50+ in stock" );
  } else if ($z:value[article.availableinstock] >=25 ) {
    document.write('<div class="shop_ok">');
    document.write(" 25+ in stock" );
  } else {
    document.write('<div class="shop_bob">');
    document.write(+ avail.toFixed(0));
    document.write(" in stock" );
  }
}

然后,在您的页面body内的某个地方,您只需致电

<script type="text/javascript">setTimeout(yourStuff, 2000);</script>

答案 1 :(得分:0)

将代码包含在函数中并使用setTimeout JS函数。

function function_name () {
    var avail=$z:value[article.availableinstock];

    if ($z:value[article.availableinstock] < 1)
    {
        document.write('<div class="shop_not">');
        document.write("In order!");
    }
    else if ($z:value[article.availableinstock] >=100)
    {
        document.write('<div class="shop_ok">');
        document.write(" 100+ in stock" );
    }
    else if ($z:value[article.availableinstock] >=50 )
    {
        document.write('<div class="shop_ok">');
        document.write(" 50+ in stock" );
    }
    else if ($z:value[article.availableinstock] >=25 )
    {
        document.write('<div class="shop_ok">');
        document.write(" 25+ in stock" );
    }
    else
    {
        document.write('<div class="shop_bob">');
        document.write(+ avail.toFixed(0));
        document.write(" in stock" );
    }
}

setTimeout('function_name()', 2000);