jQuery $(this) keyword

后端 未结 6 1155
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 15:17

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

I am using a lot of animate and css editing in my code, and I know I can simplify it by using

6条回答
  •  悲&欢浪女
    2020-11-27 16:03

    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)

    **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;
        }
    
    
    Name: John Doe
    Age: 33
    Addres: Bangladesh
    This is hidden content
    Name: John Doe
    Age: 33
    Addres: Bangladesh
    This is hidden content
    Name: John Doe
    Age: 33
    Addres: Bangladesh
    This is hidden content

提交回复
热议问题