jQuery的.data()不会将属性附加到DOMElement

时间:2015-08-01 22:52:42

标签: javascript jquery html plugins

所以我写了这个非常简单的jQuery滑块插件。我尝试使用.data()设置data-*属性,但这似乎没有任何效果,因为没有任何内容添加到DOM元素。

如果我使用.attr('data-image', myVar);,它可以正常工作。

以下是代码:

;(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);

对于这个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>

使用此插件实例:

jQuery(function($) {
    $('#slider').sdSlider();
});

这是范围问题吗?然而,我的目标是$(elem),它代表传递给插件的元素。

我在这里缺少什么?为什么data-image元素未添加到<img>元素?

1 个答案:

答案 0 :(得分:2)

jQuery.data()不会更新DOM元素HTML5 data-*属性