2013-04-26 50 views
2

我正在开发一个平台,并希望统一和标准化整个平台的某些行为...... html元素中的data-attribute将扮演巨大的角色部分...从数据attr中获取所有具有相同前缀的键/值对

因此,可以说我有一个按钮:

<a href="..." class="btn" data-tip="My button" data-modal_tile="Foo" data-templade_data_id="14" data-templade_data_action="reset">...</a> 

现在,我的Javascript处理这个按钮的行为。

我想要的是设置一个template_data数组,它会给我所有具有相同前缀的数据属性的键/值对(data-template_data _)... 所以在我的示例中,我会得到:

{ 
    id: "14", 
    action : "reset" 
} 

这样做的最佳方法是什么?

回答

3

试试这个

var array = []; 
$(".btn").each(function(){ 
    var obj = {}; 
    $.each(this.attributes, function() 
    { 
     if(this.name.indexOf("data-templade_data_") == 0) 
     { 
      var key = this.name.replace("data-templade_data_", ""); 
      obj[ key ] = this.value; 
     } 
    }); 
    array.push(obj); 
}); 
+0

好吧,谢谢...这样的事情...有点短,因为jQuery允许您使用$(el).data()访问数据,所以我只会迭代低谷数据..虽然它很直接。 .. 谢谢 – 2013-04-26 09:40:08

1

这对我的作品

jQuery.fn.extend({ 
hyphened: function(prefix) { // prefix = data or myplugin 
    var attributes = {}; 
    $.each(this.get(0).attributes, function(index, attrib) { 
     if(attrib.name.indexOf(prefix+"-")==0) { 
      var key = attrib.name.replace(prefix+"-",""); 
      attributes[key] = attrib.value; 
     } 
    }); 

    return attributes; 
} 

});

相关问题