如何检索所有数据id属性值?我尝试过使用jquery,但只获得了1个id或1个值
对于我的代码
<div class="col text-right mr-1">
<a href="" class="show_more comment-count-custom" id="show_more" data-idpost="<?= $p["id_post"] ?>">show more comments</a>
</div>
jquery
var id = $(".show_more").data("idpost");
console.log(id)
我得到的结果但仅获得1个id或1个值
要从所有.show-more
元素构建data-idpost
值的数组,可以使用map()
:
var idData = $('.show_more').map((i, el) => el.dataset.idpost).get();
console.log(idData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col text-right mr-1">
<a href="" class="show_more comment-count-custom" id="show_more" data-idpost="1">show more comments</a>
</div>
<div class="col text-right mr-1">
<a href="" class="show_more comment-count-custom" id="show_more" data-idpost="2">show more comments</a>
</div>
<div class="col text-right mr-1">
<a href="" class="show_more comment-count-custom" id="show_more" data-idpost="3">show more comments</a>
</div>
如果show_more
类为多个。您可以与Jquery#map()
和jquery.get()
一起使用api方法
var ids = $(".show_more").map((i,elem)=> $(elem).data("idpost")).get()
console.log(ids)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col text-right mr-1">
<a href="" class="show_more comment-count-custom" data-idpost="1">show more comments</a>
<a href="" class="show_more comment-count-custom" data-idpost="2">show more comments</a>
<a href="" class="show_more comment-count-custom" data-idpost="3">show more comments</a>
</div>