如何检索属性数据id值​而不点击



如何检索所有数据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>

相关内容

  • 没有找到相关文章

最新更新