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

时间:2015-01-15 21:33:47

标签: 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>

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

$('#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选择器,类似于属性启动选择器[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数组,没有我不需要的东西。

4 个答案:

答案 0 :(得分:8)

定位data-*

开头的所有元素

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

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

  

鉴于 数据 - foo-bar前缀,目标以下元素:

     

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

     

     

data-foo-someting
  data-something

&#13;
&#13;
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 );
});
&#13;
<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>
&#13;
&#13;
&#13;

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

&#13;
&#13;
$.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"});  
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

此函数将获取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')));
    });

答案 2 :(得分:0)

这是在循环数据时隔离无效键的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条件只包括你想要的那些键。

答案 3 :(得分:0)

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

用法

使用具有相同前缀的多个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');

上一个示例返回对象:

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