从数据属性解析$ .extend配置

Ale*_*lex 6 javascript jquery html5 jquery-plugins

我知道我可以使用$ .data但是如何迭代所有data-属性并将值与默认插件配置合并?

(function($){

  $.fn.plugin = function(opts){  

    opts = $.extend({
      foo: 'abc',
      boo: 45
    }, opts);

    return this.each(function(){        
          ...
    });

  };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

所以,如果我使用

$('.el').plugin();

它应该寻找数据属性.el,如data-foo等...

Fré*_*idi 5

each()循环中,您可以将data()返回的对象与默认值合并,然后opts$ .extend()的单个调用中将参数与结果合并:

$.fn.plugin = function(opts) {
    return this.each(function() {        
        var thisOpts = $.extend({
            foo: "abc",
            boo: 45
        }, $(this).data(), opts);
        // Now use 'thisOpts' as operating parameters for this element...
    });
};
Run Code Online (Sandbox Code Playgroud)

这应该达到你想要的:opts参数具有最高优先级,其次data-是当前元素的属性,后跟插件默认值.


Did*_*hys 3

.data ()方法支持数据属性。

从 jQuery 1.4.3 开始,HTML 5 数据属性将自动拉入 jQuery 的数据对象。jQuery 1.6 中对带有嵌入破折号的属性的处理进行了更改,以符合 W3C HTML5 规范。

在不指定参数的情况下调用它将返回一个包含所有数据属性的键/值对的对象:

var mydata = $("#mydiv").data();
Run Code Online (Sandbox Code Playgroud)