gpt4 book ai didi

javascript - 通过数据属性获取元素id

转载 作者:行者123 更新时间:2023-11-28 04:48:59 25 4
gpt4 key购买 nike

我有以下 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 个 demental 数组(如下所示):

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);
});

最佳答案

使用 each() 方法迭代元素并根据数据属性在内部生成对象。

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>

关于javascript - 通过数据属性获取元素id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37677991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com