Use attr () function inside new plugin?

I want to know if the attr() function can be used inside the new plugin:

 (function ($) { $.fn.resetColor = function() { var oldColor=this.attr("memColor"); this.css('background-color',oldColor); }; })(jQuery); 

I tried the code above, but it does not work. I am sure that the memColor attribute exists because I tested it with a warning in the $(document).ready block.

+5
source share
1 answer

JQuery plugin authoring guidelines recommend this method:

 (function ($) { $.fn.resetColor = function() { return this.each(function() { var elem = $( this ); var oldColor = elem.attr("memColor"); elem.css('background-color',oldColor); }; }); }(jQuery)); 
  • Suppose a plugin is called on many elements.
  • Get the processed jQuery element to work.

Also keep in mind that there is a difference between properties ( prop() ) and attributes ( attr() ), the first refers to properties in the JavaScript DOM HTMLElements , and in the future, HTML attributes as they are indicated in the markup. And jQuery makes this distinction also since version 1.6:

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr () method sometimes took property values ​​into account when retrieving certain attributes, which can lead to inconsistent behavior. Starting with jQuery 1.6, the .prop () method provides a way to explicitly retrieve property values, while .attr () retrieves attributes.


Demo:

  (function ($) { $.fn.resetColor = function() { return this.each(function() { var elem = $( this ); var oldColor = elem.attr("memColor"); elem.css('background-color',oldColor); }); }; $('.me').resetColor(); }(jQuery)); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="me" memColor="Red">Lorem ipsum.</div> <div class="me" memColor="Blue">Lorem ipsum.</div> 
+5
source

Source: https://habr.com/ru/post/1209037/


All Articles