Html将5个数据属性转换为jquery插件选项格式

Html 5 data-attributes into jquery plugin options format

本文关键字:jquery 插件 选项 格式 转换 5个 数据属性 Html      更新时间:2023-09-26

除了jquery插件选项外,我还想用html5数据属性覆盖这些值。


这是所需的选项格式是:

var defaults = {
   text: {
      color: 'red',
      opacity: 0.5
   },
   button: {
      width: 100,
      height: 30
   }
}

我想把数据属性格式化成这样:

<div data-text="color:'red', opacity: 0.5"></div>

但是您将无法读取此数据o.text.color,因为它根本不存在。然而,o.text内部有数据。

如何格式化数据属性,以便使用o.text.color获取值?

只需将格式化为json字符串的对象传递给属性,jQuery数据就会为您解析它。

<div class="test" data-test='{ "test1":"Lorem","test2":"Ipsum" }'></div>

另请参阅更新的fiddle

这不是很干净,让我想起了HTML中的onclick事件。为什么不把它们分成data-test1="Lorem"&data-test2="Ipsum"?

插件可以是这样的(扩展jquery插件样板):

function Plugin( element, options, objD ) {
    this.element = element;
    this.options = $.extend( {}, defaults, options, objD );
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
}
$.fn[pluginName] = function ( options ) {
  return this.each(function () {
    if (!$.data(this, "plugin_" + pluginName)) {
        var objD = $(this).data();
        $.data(this, "plugin_" + pluginName, new Plugin( this, options, objD ));
    }
  });
};

我不是大师,但对我来说效果很好