Guest User

Untitled

a guest
Aug 19th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. Reference current context when setting jQuery plugin options
  2. (function ($) {
  3. $.fn.colourise = function (options) {
  4. var settings = $.extend({
  5. color: "black"
  6. }, options);
  7.  
  8. return this.each(function () {
  9. $(this).css("color", options.color);
  10. });
  11. };
  12. })(jQuery);
  13.  
  14. <div data-color="red">
  15. This text should be red.
  16. </div>
  17. <div data-color="blue">
  18. This text should be blue
  19. </div>
  20. <div data-color="green">
  21. This text should be green
  22. </div>
  23.  
  24. $(function () {
  25. // This feels a bit wrong to have to use a .each() here, but how else do we do it?
  26. $("div").each(function () {
  27. $(this).colourise({
  28. color: $(this).data("color")
  29. });
  30. });
  31. });
  32.  
  33. $(function () {
  34. $("div").colourise({
  35. color: [get context of this "div" somehow].data("color")
  36. });
  37. });
  38.  
  39. function getColor(){
  40. return $.data( this, "color" );
  41. }
  42.  
  43. $(function () {
  44. $("div").colourise({
  45. color: getColor
  46. });
  47. });
  48.  
  49. (function ($) {
  50. $.fn.colourise = function (options) {
  51. var settings = $.extend({
  52. color: "black"
  53. }, options);
  54.  
  55. return this.each(function () {
  56. var color = options.color;
  57.  
  58. color = typeof color =="function" ? color.call( this ) : color;
  59. $(this).css("color", color);
  60. });
  61. };
  62. })(jQuery);
Add Comment
Please, Sign In to add comment