【问题标题】:jQuery's .data() doesn't append attribute to DOMElement [duplicate]jQuery .data() 不会将属性附加到 DOM 元素 [重复]
【发布时间】:2015-10-24 08:40:26
【问题描述】:

所以我写了这个非常简单的 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 属性没有添加到&lt;img&gt; 元素中?

【问题讨论】:

    标签: javascript jquery html plugins


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      • 2016-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多