jQuery $(this) 关键字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12481439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:44:22  来源:igfitidea点击:

jQuery $(this) keyword

jquery

提问by agassi0430

Why is it important to use $(this) instead of re-selecting the class?

为什么使用 $(this) 而不是重新选择类很重要?

I am using a lot of animate and css editing in my code, and I know I can simplify it by using $(this).

我在我的代码中使用了很多动画和 css 编辑,我知道我可以通过使用 $(this) 来简化它。

回答by Phil

When you perform an DOM query through jQuery like $('class-name')it actively searched the DOM for that element and returns that element with all the jQuery prototype methods attached.

当您通过 jQuery 执行 DOM 查询时,$('class-name')它会主动在 DOM 中搜索该元素并返回该元素以及附加的所有 jQuery 原型方法。

When you're within the jQuery chain or event you don't have to rerun the DOM query you can use the context $(this). Like so:

当您在 jQuery 链或事件中时,您不必重新运行 DOM 查询,您可以使用 context $(this)。像这样:

$('.class-name').on('click', (evt) => {
    $(this).hide(); // does not run a DOM query
    $('.class-name').hide() // runs a DOM query
}); 

$(this)will hold the element that you originally requested. It will attach all the jQuery prototype methods again, but will not have to search the DOM again.

$(this)将保存您最初请求的元素。它将再次附加所有 jQuery 原型方法,但不必再次搜索 DOM。

Some more information:

更多信息:

Web Performance with jQuery selectors

jQuery 选择器的 Web 性能

Quote from a web blog that doesn't exist anymore but I'll leave it in here for history sake:

引自一个已不存在的网络博客,但为了历史起见,我将其保留在这里:

In my opinion, one of the best jQuery performance tips is to minimize your use of jQuery. That is, find a balance between using jQuery and plain ol' JavaScript, and a good place to start is with ‘this‘. Many developers use $(this) exclusively as their hammer inside callbacks and forget about this, but the difference is distinct:

When inside a jQuery method's anonymous callback function, this is a reference to the current DOM element. $(this) turns this into a jQuery object and exposes jQuery's methods. A jQuery object is nothing more than a beefed-up array of DOM elements.

在我看来,最好的 jQuery 性能技巧之一就是尽量减少对 jQuery 的使用。也就是说,在使用 jQuery 和普通的 JavaScript 之间找到一个平衡点,最好从“this”开始。许多开发人员将 $(this) 专门用作回调中的锤子而忘记了这一点,但区别是明显的:

当在 jQuery 方法的匿名回调函数中时,这是对当前 DOM 元素的引用。$(this) 将 this 转换为 jQuery 对象并公开 jQuery 的方法。jQuery 对象只不过是增强的 DOM 元素数组。

回答by Dejo Dekic

$(document).ready(function(){
   $('.somediv').click(function(){
   $(this).addClass('newDiv'); // this means the div which is clicked
   });                         // so instead of using a selector again $('.somediv');
});                           // you use $(this) which much better and neater:=)

回答by Angad

Have a look at this code:

看看这个代码:

HTML:

HTML:

<div class="multiple-elements" data-bgcol="red"></div>
<div class="multiple-elements" data-bgcol="blue"></div>

JS:

JS:

$('.multiple-elements').each(
    function(index, element) {
        $(this).css('background-color', $(this).data('bgcol')); // Get value of HTML attribute data-bgcol="" and set it as CSS color
    }
);

thisrefers to the current element that the DOM engine is sort of working on, or referring to.

this指当前元素的DOM发动机是排序的工作,或参照

Another example:

另一个例子:

<a href="#" onclick="$(this).css('display', 'none')">Hide me!</a>

Hope you understand now. The thiskeyword occurs while dealing with objectoriented systems, or as we have in this case, elementoriented systems :)

希望你现在明白。将this在处理时关键字对象导向系统,或者我们在这种情况下,元素的面向系统:)

回答by Teena Thomas

using $(this) improves performance, as the class/whatever attr u are using to search, need not be searched for multiple times in the entire webpage content.

使用 $(this) 可以提高性能,因为您用来搜索的类/任何属性都不需要在整个网页内容中多次搜索。

回答by Numan

I'm going to show you an example that will help you to understand why it's important.

我将向您展示一个示例,以帮助您理解为什么它很重要。

Such as you have some Box Widgets and you want to show some hidden content inside every single widget. You can do this easily when you have a different CSS class for the single widget but when it has the same class how can you do that?
Actually, that's why we use $(this)

例如,您有一些 Box 小部件,并且希望在每个小部件中显示一些隐藏的内容。当您为单个小部件使用不同的 CSS 类时,您可以轻松地做到这一点,但是当它具有相同的类时,您如何做到这一点?
实际上,这就是为什么我们使用$(this)

**Please check the code and run it :) ** enter image description here

**请检查代码并运行它 :) ** 在此处输入图像描述

  (function(){ 

            jQuery(".single-content-area").hover(function(){
                jQuery(this).find(".hidden-content").slideDown();
            })

            jQuery(".single-content-area").mouseleave(function(){
                jQuery(this).find(".hidden-content").slideUp();
            })
             
        })();
  .mycontent-wrapper {
      display: flex;
      width: 800px;
      margin: auto;
    }     
    .single-content-area  {
        background-color: #34495e;
        color: white;  
        text-align: center;
        padding: 20px;
        margin: 15px;
        display: block;
        width: 33%;
    }
    .hidden-content {
        display: none;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mycontent-wrapper">
    <div class="single-content-area">
        <div class="content">
            Name: John Doe <br/>
            Age: 33  <br/>
            Addres: Bangladesh
        </div> <!--/.normal-content-->
        <div class="hidden-content">
            This is hidden content
        </div> <!--/.hidden-content-->
    </div><!--/.single-content-area-->

    <div class="single-content-area">
        <div class="content">
            Name: John Doe <br/>
            Age: 33  <br/>
            Addres: Bangladesh
        </div> <!--/.normal-content-->
        <div class="hidden-content">
            This is hidden content
        </div> <!--/.hidden-content-->
    </div><!--/.single-content-area-->


    <div class="single-content-area">
        <div class="content">
            Name: John Doe <br/>
            Age: 33  <br/>
            Addres: Bangladesh
        </div> <!--/.normal-content-->
        <div class="hidden-content">
            This is hidden content
        </div> <!--/.hidden-content-->
    </div><!--/.single-content-area-->

</div><!--/.mycontent-wrapper-->

回答by Operator

$(this)returns a cachedversion of the element, hence improving performance since jQuery doesn't have to do a complete lookup in the DOM of the element again.

$(this)返回cached元素的一个版本,从而提高性能,因为 jQuery 不必再次在元素的 DOM 中进行完整查找。