我有div标签,如下所示
<div class="class" data-mark-comp="comp1" data-conf-property1="p1" data-conf-property2="p2" data-conf-property3="p3"</div>
我想创建一个由data-conf- *属性组成的对象
var conf = $(".class").data() <br>
我尝试了上面的内容,但它包含了我根据我的要求不需要的所有属性.
var conf = $(".class").data("conf-*") - this one also not working
最佳答案 一种方法是创建自己的插件.
这个接受正则表达式与财产进行比较: –
$.fn.ddata = function(regex) {
var objs = [];
this.each(function() {
var obj = {};
for (var prop in this.dataset)
if (regex.test(prop))
obj[prop] = this.dataset[prop];
objs.push(obj);
});
return objs;
};
var conf = $('.class').ddata(/^conf/);
console.log(conf);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class" data-mark-comp="comp1" data-conf-property1="p1" data-conf-property2="p2" data-conf-property3="p3"></div>