jQuery $(this) keyword

后端 未结 6 1141
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  萌比男神i
    2020-11-27 15:52

    Have a look at this code:

    HTML:

    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
        }
    );
    

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

    Another example:

    Hide me!
    

    Hope you understand now. The this keyword occurs while dealing with object oriented systems, or as we have in this case, element oriented systems :)

提交回复
热议问题