jQuery's .data() doesn't append attribute

2019-09-19 11:18发布

This question already has an answer here:

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?

1条回答
等我变得足够好
2楼-- · 2019-09-19 12:02

jQuery.data() does not update DOM elements HTML5 data-* attribute

查看更多
登录 后发表回答