【问题标题】:If this() selector is used inside a function, which selector will it refer to (jQuery)?如果 this() 选择器在函数内部使用,它将引用哪个选择器(jQuery)?
【发布时间】:2011-08-31 16:18:05
【问题描述】:
例如我有一个函数:
function somefunction () {
$('someselector').fadeOut('slow', function() { $(this).remove; });
}
然后这个函数在内部被调用:
$('someselector1').click(function() {
somefunction ();
});
somefunction() 中的$(this) 是指someselector() 还是someselector1()?据我了解,this() 指的是触发事件的选择器,在本例中为 someselector1。对吗?
【问题讨论】:
标签:
javascript
jquery
function
css-selectors
【解决方案1】:
它将引用匹配someselector 的DOM 元素。 this 设置为正在应用 fadeOut 函数的元素。
someFunction 内部的this(但不在fadeOut 的回调函数内部)将是对window 对象的引用。
function somefunction () {
// "this", unless specifically set, will refer to "window"
$('someselector').fadeOut('slow', function() {
// "this" refers to the element that just finished fading out.
$(this).remove;
});
}
示例: http://jsfiddle.net/9ubgH/
【解决方案2】:
请注意,$(this) 语法并没有什么神奇之处——它只是将this 指向的任何东西提供给(重载的)主 jQuery 入口点,而 jQuery 的作用完全取决于什么样的事情是这样的。特别是,JQuery 不知道您从 this 获得了它的参数。
这是相关的,因为仅仅在一个函数中并不能告诉你this 将是什么——这或多或少取决于函数的调用者来决定。在您的情况下,该函数恰好是从将 this 设置为可预测的代码的代码中调用的,但对于 一般的函数,这不是您可以假设的。
【解决方案3】:
它将引用someselector。
$('someselector').fadeOut('slow', function() { $(this).remove; });
在上面的fadeOut 回调中this 将指向它正在消失的元素,因此this 将指向someselector。