在命名方法中处理`this`关键字

时间:2014-02-28 17:34:56

标签: jquery

一个非常简单的问题,但我想得到你的意见:

function return_this_normal(){
//    console.log($(this));
     $(this).css('color','green');

}

$('.normal').mouseover( function(){
//        console.log($(this));
        $(this).css('color','red');
        return_this_normal()
   }
);

现在,上面的脚本在悬停时将'.normal'div的文本变为红色。您可能希望它将其变为绿色,因为它会在文本变为红色并return_this_normalreturn_this_normal的css更改为绿色后调用this

然而,它并不是因为this中的return_this_normal不返回元素,而实际函数本身如何存在于浏览器的内存中(或类似的东西)。我只想说,更新这个函数的CSS并没有任何作用。

现在要解决这个问题,我们可以简单地将.normal元素作为参数传递给return_this_normal()函数,但我只是想知道在jquery中是否有标准化的方法来执行此操作将元素传递给命名函数似乎是非常常见的功能。

http://jsfiddle.net/Ea5Rh/3/

2 个答案:

答案 0 :(得分:2)

如果要向jQuery添加函数,那么可以运行$(element).my_function(),然后将其添加到$.fn对象。在该函数中,this按预期设置。

$.fn.return_this_normal = function(){
     return this.css('color','green');       
}

$('.normal').mouseover( function(){
        $(this).css('color','red');
        $(this).return_this_normal();
   }
);

注意我从函数返回以支持jQuery的链接语法。

否则你应该将this作为参数传递给你的函数,如果函数不是该对象的一个​​成员,这是很正常的事情。

答案 1 :(得分:0)

将此传递给return_this_normal,因为这仅适用于鼠标悬停的处理程序

<强> Live Demo

/* Normal */
function return_this_normal(ob){
   // console.log($(this));
     $(ob).css('color','green');

}

$('.normal').mouseover( function(){
//        console.log($(this));
        $(this).css('color','red');
        return_this_normal(this)
   }
);

您也可以使用.call()

传递此内容

<强> Live Demo

/* Normal */
function return_this_normal(){
    console.log($(this));
     $(this).css('color','green');

}

$('.normal').mouseover( function(){
//        console.log($(this));
        $(this).css('color','red');
        return_this_normal.call(this)
   }
);