如果this()选择器在函数中使用,它将引用哪个选择器(jQuery)

If this() selector is used inside a function, which selector will it refer to (jQuery)?

本文关键字:选择器 引用 jQuery this 函数 如果      更新时间:2023-09-26

例如我有一个函数:

function somefunction () {
    $('someselector').fadeOut('slow', function() { $(this).remove; });
}

则在

内部调用该函数:
$('someselector1').click(function() {
     somefunction ();
});

somefunction()里面的$(this)是指someselector()还是指someselector1() ?正如我所理解的,this()指的是触发事件的选择器,在这种情况下,是someselector1。对吗?

表示匹配someselector的DOM元素。this设置为fadeOut函数正在应用的元素。

thissomeFunction内(但不在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/

请注意,$(this)语法并没有什么神奇之处——它只是将this指向的内容提供给(重载的)jQuery主入口点,而jQuery所做的完全取决于它是什么类型的东西。特别是,JQuery 不知道你从this获得了它的参数。

这是相关的,因为仅仅存在于函数中并不能告诉您this将是什么——这或多或少取决于函数的调用者来决定。在您的情况下,函数恰好是从将this设置为可预测的代码中调用的,但这不是您可以假设的一般函数

someselector

$('someselector').fadeOut('slow', function() { $(this).remove; });

在上面的fadeOut回调中,this将指向它正在褪色的元素,因此this将指向someselector

在本例中,它指的是" someeselector "。

查看此提琴http://jsfiddle.net/6gdnw/