Lets say I have the following jQuery plugin (this is just an example to demonstrate the point):
(function ($) {
$.fn.colourise = function (options) {
var settings = $.extend({
color: "black"
}, options);
return this.each(function () {
$(this).css("color", options.color);
});
};
})(jQuery);
which I want to apply to the following markup:
<div data-color="red">
This text should be red.
</div>
<div data-color="blue">
This text should be blue
</div>
<div data-color="green">
This text should be green
</div>
If the value I want to pass as one of the options of a plugin depends on the element, how do I apply it? At the moment I can only get this working by doing:
$(function () {
// This feels a bit wrong to have to use a .each() here, but how else do we do it?
$("div").each(function () {
$(this).colourise({
color: $(this).data("color")
});
});
});
I.e. by iterating over each one with the .each() method and applying the plugin to each element individually (which kinda makes the this.each() inside the plugin a bit redundant). It feels like I should be able to do something like:
$(function () {
$("div").colourise({
color: [get context of this "div" somehow].data("color")
});
});
But I can’t use $(this) or this here because they refer to the document.
Sorry for the lack of a http://jsfiddle.net/, but the site is really slow for me at the moment, they must be having a few issues.
.eachis exactly what you need.When you call the method on a multi-element set without a
.eachcallback, you’re creating a single options object that gets used within the plugin for every element in the set.You can’t vary it per-element without making a separate object for each element.