如何通过前缀获取所有data- *属性

我有这样的标签:

Link 

当我点击这个链接时,我有这样的function

 $('#ssd').click(function (event) { var customData; // Code to get all the custom data in format like data-info* }); 

请注意,data-info * like属性可以是任意数字,这意味着您可以看到其中一个名为data-info1或其中的名为data-info1,data-info2,data-info3。

我如何做到这一点,我查找了JQuery选择器,类似属性启动选择器[名称^ =“值”]将无法工作,因为这里的变化是名字…

如果我是console.log($('#ssd').data()); 我将获得一个具有我不需要的额外属性的对象, toggle: "popover", bs.popover: Popover

有什么建议?

这就是我做的:

 dataFullList = $(this).data(); $.each(dataFullList, function (index, value) { if (index !== "toggle" && index !== "bs.popover") { item.name = value.split(":")[0]; item.number = value.split(":")[1]; dataIWant.push(item); } }); 

所以我将得到一个dataIWant数组,没有我不需要的东西。

定位data-*开头的所有元素

自定义jQuery选择selector:dataStartsWith()选择selector:dataStartsWith()

这是一个自定义jQuery选择器,可以帮助您:

给定data foo-bar前缀, 定位以下元素:

data-foo-bar
data-foo-bar-baz

不是

data-foo-someting
data-something

 jQuery.extend(jQuery.expr[':'], { "dataStartsWith" : function(el, i, p, n) { var pCamel = p[3].replace(/-([az])/ig, function(m,$1) { return $1.toUpperCase(); }); return Object.keys(el.dataset).some(function(i, v){ return i.indexOf(pCamel) > -1; }); } }); // Use like: $('p:dataStartsWith(foo-bar)').css({color:"red"}); // To get a list of data attributes: $('p:dataStartsWith(foo-bar)').each(function(i, el){ console.log( el.dataset ); }); 
  

I have data-foo-bar

I have data-foo-bar-baz

I have data-bar DON'T SELECT ME

I have data-something DON'T SELECT ME

此函数将获取data-info属性并将它们放入数组中:

  function getDataInfo($element, i, a) { var index = i || 1, array = a || [], info = $element.data('info' + index); if(info === undefined) { return array; } array['info' + index] = info; return getDataInfo($element, index + 1, array); } $(function() { console.log(getDataInfo($('#ssd'))); }); 

这是在循环数据时隔离无效键的if条件。 用作filter,您可以选择删除不需要的键 – 如下所示:

 $('#ssd').click(function(e){ var data = $(this).data(); for(var key in data) { //here is a condition to use only those data-info items if(data.hasOwnProperty(key) && key.indexOf('info') === -1) { console.log(key); //just to see which key it is delete data[key]; //if you need to build a collection of only data-info keys } } }); 

或者,否定if条件以仅包含您想要的那些键。