为什么只显示Alert 3 ???

时间:2015-03-16 18:15:57

标签: jquery html

为什么只显示Alert 3 ???怎么了???回调解决了吗?怎么样?

CSS:

#foo {
    width: 200px;
    height: 30px;
    display: none;
    background-color: red;
}

HTML:

<div id="foo"><div>

Jquery的:

$('#foo').text('Alert 1').show(0).delay(5000).hide(0);

$('#foo').text('Alert 2').show(0).delay(5000).hide(0);

$('#foo').text('Alert 3').show(0).delay(5000).hide(0);

1 个答案:

答案 0 :(得分:2)

它实际上显示“警报1”,然后显示“警报2”,然后显示“警报3”,但是您的眼睛看得太快,甚至显示器都显示它。 这些行是顺序执行的。在执行第2行之前,代码不等待第1行及其5000ms延迟结束。

PHP会这样做,因为那是一种同步语言。

Javascript没有,因为它是异步的:它可以同时做很多事情。

为了使每个警报等待5000毫秒,您需要设置回调函数:在某些事情结束后执行的函数。

$('#foo')
	.text('Alert 1')
	.show()
	.delay(3000)
	.hide(0, showAlert2 )

function showAlert2(){
	$('#foo')
		.text('Alert 2')
		.show()
		.delay(3000)
		.hide(0, showAlert3 )
}

function showAlert3(){
	$('#foo')
		.text('Alert 3')
		.show()
		.delay(3000)
		.hide(0)
}
#foo {
    width: 200px;
    height: 30px;
    display: none;
    background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="foo"><h1>

修改1

这个例子很丑陋,它重复代码,但它是出于教育目的。如果要显示许多警报,则会将代码分解(而不是重复):

var i=0;

function showAlert(){
  i++;
  $('#foo')
    .text('Alert '+i)
    .show()
    .delay(3000)
    .hide(0, showAlert)
}

showAlert(i)
#foo {
        width: 200px;
        height: 30px;
        display: none;
        background-color: red;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h1 id="foo"><h1>

修改2

或者再次提供警报列表:

var alerts = ['alert 1', 'alert 2', 'alert 3', 'alert 4'],
    i = 0;

function showAlert(){

  $('#foo')
    .text(alerts[i])
    .show()
    .delay(3000)
    .hide(0, showAlert)
  
  if(i>alerts.length) return;
  i++;
}

showAlert(i)
#foo {
        width: 200px;
        height: 30px;
        display: none;
        background-color: red;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h1 id="foo"><h1>