Javascript - 在函数内的函数中使用 $(this)
Javascript - using $(this) in a function inside a function?
基本上,有一个屏幕,如果你链接一个按钮,屏幕会向上滑动,然后出现另一个屏幕。问题是,slideUp() 函数需要一些时间来执行,并且在 slideUp 函数完成执行之前出现另一个屏幕。我希望它使另一个屏幕等到slideUp功能执行完毕,直到另一个屏幕出现。以下是主要的Javascript:
$('#sidebar ul li a').click(function(){
$('#sidebar ul .clicked').removeClass('clicked'); // when an <a> is clicked, remove .clicked class from any other <a>'s
$(this).addClass('clicked');
hidePrevSlide(); //this calls slideUp in the current screen
$(this).showCurrentSlide(); //this shows another screen before hidePrevSlide is even finished executing / sliding Up
});
我试过了
hidePrevSlide(function(){
$(this).showCurrentSlide();
});
但是由于某种原因,这会破坏代码。有什么方法可以完成我正在做的事情吗?
试试这个:
$('#sidebar ul li a').click(function(){
$('#sidebar ul .clicked').removeClass('clicked'); // when an <a> is clicked, remove .clicked class from any other <a>'s
$(this).addClass('clicked');
var current_slide=$(this);
hidePrevSlide(function(){
current_slide.showCurrentSlide();
});
$(this).showCurrentSlide(); //this shows another screen before hidePrevSlide is even finished executing / sliding Up
});
我可以看到您遇到了范围界定问题。通过在函数之前存储$(this)
,您将能够在下面的函数中访问该变量。
对于一个小的优化,你应该避免使用多个$(this)
这样我们就可以重用我们的current_slide
变量,如下所示:
$('#sidebar ul li a').click(function(){
var current_slide=$(this);
$('#sidebar ul .clicked').removeClass('clicked'); // when an <a> is clicked, remove .clicked class from any other <a>'s
current_slide.addClass('clicked');
hidePrevSlide(function(){
current_slide.showCurrentSlide();
});
current_slide.showCurrentSlide(); //this shows another screen before hidePrevSlide is even finished executing / sliding Up
});
相关文章:
- 在另一个函数中使用变量this
- JavaScript 中的嵌套函数和 “this” 关键字
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- 在JavaScript类型的函数中避免self-this
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- jQuery使用ajax自动完成问题-TypeError:this.source不是函数
- 为什么在这种情况下,“This”确实充当javascript函数中的私有成员
- TypeError:this.getAttribute不是一个函数-javascript
- CasperJS error - undefined 不是函数 (this.waitForUrl)
- AngularJs服务函数this()
- 内联onclick函数(this)不调用jQuery方法
- jQuery自定义函数- this.each
- 为什么在构造函数'this'DOMWindow
- 调用匿名函数'this'从函数
- Javascript检查函数(this)的长度
- 如何使用onchange="函数(this.value)
- 改变一个函数"this"值
- javascript构造函数this is't绑定正确
- JS原型函数'this'混乱