我多次访问$(this)时应该创建一个局部变量$ this吗?

cap*_*ill 1 javascript jquery

例:

$("#footer-create-nav li").click(function () {
    var $this = $(this);
    $this.addClass('footer-create-active');
    $this.siblings().removeClass('footer-create-active');
    return false;
}
Run Code Online (Sandbox Code Playgroud)

与我的代码看起来很多:

$("#footer-create-nav li").click(function () {
    $(this).addClass('footer-create-active');
    $(this).siblings().removeClass('footer-create-active');
    return false;
}
Run Code Online (Sandbox Code Playgroud)

Anu*_*rag 5

避免多次重新创建jQuery对象是一种很好的做法.

this表示一个DOM对象,当传递给$or或jQuery函数时,每次都会创建一个新的jQuery对象.缓存该对象一次$this或您喜欢的任何其他变量名称避免了必须在每次调用时重新创建对象$(this).此缓存的好处可能取决于您呼叫的次数,$(this)并且在大多数情况下可能无法察觉.

为了获得更好的想法,请为自己测试一下.