This question already has an answer here:
- jQuery Data vs Attr? 3 answers
So I have this very simple jQuery slider plugin I wrote. I try to set data-*
attribute with .data()
but this seems to have no effect as nothing is added to the DOM element.
If I use .attr('data-image', myVar);
it works though.
Here is the code:
;(function($) {
$.fn.extend({
sdSlider: function(options) {
if (options && typeof(options) == 'object') {
options = $.extend({}, $.sdSlider.defaults, options);
}
if($(this).length == 1) {
new $.sdSlider(this, options);
}
return this;
}
});
$.sdSlider = function(elem, option) {
$(window).on('load', function() {
var options = option || $.sdSlider.defaults
, $li = $(elem).find('> li')
, $img = $li.find('> img')
, imgSrcs = [];
$(elem).find('> li:first-child').addClass('active');
$img.each(function(i) {
$(this).data('image', i); // this doesn't work
$(this).attr('data-image', i); // this, however, works
});
// much more code
return;
});
};
// much more code too...
$.sdSlider.defaults = {};
})(jQuery);
For this HTML:
<ul id="slider">
<li><img src="http://lorempixel.com/700/350/sports/1" alt="slider_1"/></li>
<li><img src="http://lorempixel.com/750/300/sports/2" alt="slider_2"/></li>
<li><img src="http://lorempixel.com/600/200/sports/3" alt="slider_3"/></li>
<li><img src="http://lorempixel.com/550/400/sports/4" alt="slider_4"/></li>
</ul>
With this plugin instanciation:
jQuery(function($) {
$('#slider').sdSlider();
});
So is this a problem of scope? Yet I'm targetting $(elem)
at the very beginning which represents the element passed to the plugin.
What am I missing here? Why is the data-image
attribute not added to the <img>
element?