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

How to get all data-* attributes by Prefix

我有一个这样的标签:

<a href="#" id="ssd" data-toggle="popover" data-info1="demo text: 1" data-info2="demo text: 2" data-info3="demo text3">Link</a>

当我点击这个link时,我有一个这样的功能

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

注意,data-info* 之类的属性可以是任意数字,这意味着您可以看到其中的 1 个,名为 data-info1,或者其中的一个,名为 data-info1、data-info2、data- info3.

我该怎么做,我查找了 JQuery 选择器,像 Attribute Starts With Selector [name^="value"] 这样的东西不起作用,因为这里的变体是名字。 ..

如果我 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-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 条件,用于在循环数据时隔离无效键。用作过滤器,你可以选择删除你不想要的键——像这样:

$('#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 条件以仅包含您想要的那些键。

定位 data-*

开头的所有元素

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

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

Given the data-foo-bar prefix , target the following elements:

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

but not:

data-foo-someting
data-something

jQuery.extend(jQuery.expr[':'], { 
  "dataStartsWith" : function(el, i, p, n) {  
    var pCamel = p[3].replace(/-([a-z])/ig, function(m,) { return .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 );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p data-foo-bar="a">I have data-foo-bar</p>
<p data-foo-bar-baz="b" data-extra="bbb">I have data-foo-bar-baz</p>
<p data-bar="a">I have data-bar DON'T SELECT ME</p>
<p data-something="b">I have data-something DON'T SELECT ME</p>

自定义jQuery方法$().dataStartsWith()

$.fn.dataStartsWith = function(p) {
  var pCamel = p.replace(/-([a-z])/ig, function(m,) { return .toUpperCase(); });
  return this.filter(function(i, el){
    return Object.keys(el.dataset).some(function(v){
      return v.indexOf(pCamel) > -1;
    });
  });
};


$('p').dataStartsWith("foo-bar").css({color:"red"});  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p data-foo-bar="a">I have data-foo-bar</p>
<p data-foo-bar-baz="b" data-extra="bbb">I have data-foo-bar-baz</p>
<p data-bar="a">I have data-bar DON'T SELECT ME</p>
<p data-something="b">I have data-something DON'T SELECT ME</p>

您可以使用 Prefix Data。它是 jQuery 插件。 Return 匹配元素集中第一个元素的前缀数据存储中的值。 Returned 值可以是基于属性值和属性名称结构的对象。

用法

采用具有相同前缀的多个 data-* 属性的任何 HTML 标签。在示例中我们关注 myprefix 前缀。

<div id="example-tag"
     data-myprefix='{"property1": "value1", "property2": {"property21": "value21"}, "property3": "value2"}'
     data-myprefix-property2='{"property22": "value22"}'
     data-myprefix-property2-property23="value23"
     data-myprefix-property3="overwite-value3"
     data-myprefix-property4='{"property41": "value41"}'
     data-other="We do not read it"></div>

如果您想从 data-myprefix 和每个 data-myprefix-* 属性中读取数据,您可以使用带有给定前缀的 .prefixData()

$('#example-tag').prefixData('myprefix');

前面的例子returns对象:

{
    property1: "value1",
    property2: {
        property21: "value21",
        property22: "value22",
        property23: "value23"
    },
    property3: "overwite-value3",
    property4: {
        property41: "value41"
    }
}