как получить значения атрибута data-id, не нажимая - PullRequest
1 голос
/ 18 марта 2020

Как получить все значения атрибута data-id? Я попытался использовать jquery, но для моего кода

получен только 1 идентификатор или 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 идентификатор или 1 значение

Ответы [ 2 ]

1 голос
/ 18 марта 2020

Чтобы построить массив значений data-idpost из всех элементов .show-more, вы можете использовать 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>
0 голосов
/ 18 марта 2020

Если класс show_more несколько

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...