按数据属性获取元素ID

时间:2016-06-07 11:21:27

标签: javascript jquery html

我有以下html输出:

...
<ul id="commentlist">
    <li id="comment-12" data-post="post-1">Comment 1 for post 1</li>
    <li id="comment-34" data-post="post-1">Comment 2 for post 1</li>
    <li id="comment-56" data-post="post-1">Comment 3 for post 1</li>
</ul>
<ul id="commentlist">
    <li id="comment-78" data-post="post-2">Comment 1 for post 2</li>
    <li id="comment-90" data-post="post-2">Comment 2 for post 2</li>
</ul>
...

请帮我用jQuery生成2个dementional数组(如下所示):

array = [
    "post-1": ["comment-12", "comment-34", "comment-56"],
    "post-2": ["comment-78", "comment-90"] 
]

我试过了:

jQuery("li[data-post]").each(function(){
    /*console.log(jQuery(this)); -- this contains necessary "id" but I don't know how to fetch it*/

    var testdata = jQuery(this).data('post');
    if (comment_lists.indexOf(testdata) == -1)
        comment_lists.push(testdata);
});

4 个答案:

答案 0 :(得分:4)

使用 .NET Fiddle 方法迭代元素并根据数据属性生成对象。

var obj = {};

// select elements with the attribute and iterate
$('[data-post]').each(function() {
  // get data attribute value
  var d = $(this).data('post');
  // define the property if not already defined
  obj[d] = obj[d] || [];
  // push the id of element
  obj[d].push(this.id)
})

console.log(obj)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="commentlist">
  <li id="comment-12" data-post="post-1">Comment 1 for post 1</li>
  <li id="comment-34" data-post="post-1">Comment 2 for post 1</li>
  <li id="comment-56" data-post="post-1">Comment 3 for post 1</li>
</ul>
<ul id="commentlist">
  <li id="comment-78" data-post="post-2">Comment 1 for post 2</li>
  <li id="comment-90" data-post="post-2">Comment 2 for post 2</li>
</ul>

答案 1 :(得分:1)

您可以使用对象来返回数据,而不是数组

&#13;
&#13;
var obj = {};

$('ul').each(function() {
  var li = $(this).find('li');
  obj[li.data('post')] = li.map(function() {return $(this).attr('id') }).get();
})

console.log(obj)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="commentlist">
  <li id="comment-12" data-post="post-1">Comment 1 for post 1</li>
  <li id="comment-34" data-post="post-1">Comment 2 for post 1</li>
  <li id="comment-56" data-post="post-1">Comment 3 for post 1</li>
</ul>
<ul id="commentlist">
  <li id="comment-78" data-post="post-2">Comment 1 for post 2</li>
  <li id="comment-90" data-post="post-2">Comment 2 for post 2</li>
</ul>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

最简单的解决方案是迭代所有[data-post]元素并将它们写入对象。

var array = {};

$('[data-post]').each(function(idx, el){
  var name = $(el).attr('data-post');
  if (!array.hasOwnProperty(name) {
    array[name] = [];
  }

  array[name].push($(el).attr('id'));
});

答案 3 :(得分:1)

var data = {};

$('ul li').each(function(){
    var post_name = $(this).data('post');

    if(!data[post_name])
        data[post_name] = [];

    data[post_name].push($(this).text());
});

console.log(data);