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

Xin*_* Ma 3 javascript jquery html5 twitter-bootstrap

我有这样的标签:

<a href="#" id="ssd" data-toggle="popover" data-info1="demo text: 1" data-info2="demo text: 2" data-info3="demo text3">Link</a>
Run Code Online (Sandbox Code Playgroud)

当我点击此链接时,我有这样的功能

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

请注意,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);
    }
});
Run Code Online (Sandbox Code Playgroud)

所以我会得到一个dataIWant没有我不需要的东西的数组.

Rok*_*jan 8

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

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

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

给定数据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(/-([a-z])/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 );
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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

$.fn.dataStartsWith = function(p) {
  var pCamel = p.replace(/-([a-z])/ig, function(m,$1) { return $1.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"});  
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)