你的代码里,用了两个this,但是这两个this所代表的对象是不同的。
第一个this,是在class为.hide_this的HTML控件的click事件方法里,代表的是$(hide_this)所筛选到的HTML控件对象;
而另一个this是在$(this).parents('.m_box')的animate方法的回调函数里,这个this代表的则是$(this).parents('.m_box')所筛选到的HTML控件对象,你再在animate的回调函数里用.$(this).parents('.m_box')去筛选其父层的class为.m_box的控件,即便找到了,也不是现在这个已经变透明的控件。
按照你的现在的实现逻辑,你的代码修改成下面这个样子就可以了:
$('.hide_this').click(function(){
var source = this;
$(source).parents('.m_box').animate({opacity:'0.3'},2000, function(){
$(source).parents('.m_box').animate({opacity:'1'},2000)
}) 另外可以更简单一些来处理:
$('.hide_this').click(function(){
$(this).parents('.m_box').animate({opacity:'0.3'},2000, function(){
$(this).animate({opacity:'1'},2000)
}) 对于this关键字,在什么时候,什么地方会代表什么对象,你自己应该尽量多熟悉一下。
下面是我自己测试的代码:
<html>
<head>
<script type=text/javascript src=></script>
<script language=javascript>
$(document).ready(function(){
$(#opCmd).click(function(){
$(this).parent(div).animate({opacity:'0.3'},2000,function(){
$(this).animate({opacity:'1'},2000)
});
});
});
</script>
</head>
<body >
<div id=div1 style=width:200px;height:300px;background-color:red>
<button id=opCmd>设置透明</button>
</div>
</body>
</html>