今天晚上闲下来想去试试Jquery的animate函数,本来想随便写个看看效果,兰侯就去吃饭的,结果。。。。

先来看看刚开始写的吧


<html>
<head>
	<script src="http://code.jquery.com/jquery-1.9.1.min.js" language="Javascript"></script>
	<script>
		$(function(){
			$(".green").click(function(){
				$(this).animate({top : "300px"},300,"linear",function(){
					thi = $(this);
					setTimeout(function(){
						thi.animate({top : "100px"},300);
					},1000);
				});
			});
		})
	</script>
	<style>
		.green{
			position : relative;
			float : left;
			top : 100px;
			left : 200px;
			margin : 10px;
			height : 100px;
			width : 100px;
			background-color : green;
		}
	</style>
</head>
<body>
	<div class="green"></div>
</body>
</html>

特别简单的代码,就是看看animate的效果,木有其他的想法,运行起来也木有问题。。。


本来这样就行了嘛,大家都好好的,结果,好吧,我手贱了,我多加了两个div,然后就。。。。


<html>
<head>
	<script src="http://code.jquery.com/jquery-1.9.1.min.js" language="Javascript"></script>
	<script>
		$(function(){
			$(".green").click(function(){
				$(this).animate({top : "300px"},300,"linear",function(){
					thi = $(this);
					thi.html("111");
					setTimeout(function(){
						thi.html("222");
						thi.animate({top : "100px"},300);
					},1000);
				});
			});
		})
	</script>
	<style>
		.green{
			position : relative;
			float : left;
			top : 100px;
			left : 200px;
			margin : 10px;
			height : 100px;
			width : 100px;
			background-color : green;
		}
	</style>
</head>
<body>
	<div class="green"></div>
	<div class="green"></div>
	<div class="green"></div>
</body>
</html>

额,当我快速将三个div都点击下去之后,好吧,我惊喜的发现只有最后一个起来了,而前两个都木有反应啊。。。。


蛋疼的人总是这样,然后就找原因呗,寻思了一下,感觉是因为setTimeout里使用的thi变量被覆盖的缘故。。。。

加了个输出后发现,应该就是这个的缘故,但是这是为什么呢?不是应该互不影响的么?

晚上睡觉的时候,我突然间想到一件事,没有用var声明的变量会变成全局变量,会不会是因为这个? 果断起来试了一下,问题就这么解决了。。。。

<html>
<head>
	<script src="http://code.jquery.com/jquery-1.9.1.min.js" language="Javascript"></script>
	<script>
		$(function(){
			$(".green").click(function(){
				$(this).animate({top : "300px"},300,"linear",function(){
					var thi = $(this);
					thi.html("111");
					setTimeout(function(){
						thi.html("222");
						thi.animate({top : "100px"},300);
					},1000);
				});
			});
		})
	</script>
	<style>
		.green{
			position : relative;
			float : left;
			top : 100px;
			left : 200px;
			margin : 10px;
			height : 100px;
			width : 100px;
			background-color : green;
		}
	</style>
</head>
<body>
	<div class="green"></div>
	<div class="green"></div>
	<div class="green"></div>
</body>
</html>

好吧,一失足成千古恨,我就是一个失足少年呀~  现在觉的前端的编程规范真的很重要,以后要好好学习了。。。。


再兰候就是博客升了个级,貌似代码运行的插件不能用了,就先这样吧,最近也在准备弄VPS,博客这就先这样了,以后有时间了再好好弄弄。。。


就是这样。。。。 嗯嗯。。。。

标签: js

添加新评论