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);
我想对以下标记适用:
<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>
如果我想要把价值作为原始选择之一,取决于这一要素,那么我如何适用这一要素? 目前,我只能通过这样做:
$(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")
});
});
但是,我可以不使用(这笔)美元,或因为提及该文件。