获取数组中的数据属性值和HTML

时间:2018-06-19 13:02:22

标签: javascript jquery

我的html中有以下标记,我需要将data-id值和内部html值选择到一个数组中。

我该如何在Jquery或Javascript中实现

<li class="dual-listbox__item" data-id="1">Politieacademie</li>
<li class="dual-listbox__item" data-id="3">IBM</li>
<li class="dual-listbox__item dual-listbox__item--selected" data-id="5">Energias de Portugal</li>

3 个答案:

答案 0 :(得分:3)

您可以将.map().get()一起使用,以将其转换为基本数组

var arr = $('li.dual-listbox__item').map(function() {
  return {
    id: $(this).data('id'),
    text: $(this).html()
  };
}).get();

console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="dual-listbox__item" data-id="1">Politieacademie</li>
  <li class="dual-listbox__item" data-id="3">IBM</li>
  <li class="dual-listbox__item dual-listbox__item--selected" data-id="5">Energias de Portugal</li>
</ul>

答案 1 :(得分:3)

选择元素,使用map循环它们,就可以得到数组。下面将返回包含所需数据的对象数组

const res = Array.from(document.querySelectorAll('.dual-listbox__item')).map(e => ({
  dataId: e.dataset.id,
  innerHTML: e.innerHTML
}));

console.log(res);
<li class="dual-listbox__item" data-id="1">Politieacademie</li>
<li class="dual-listbox__item" data-id="3">IBM</li>
<li class="dual-listbox__item dual-listbox__item--selected" data-id="5">Energias de Portugal</li>

答案 2 :(得分:2)

您可以使用$('.dual-listbox__item').each()来实现:

var dataId = [];
var nHTML = [];
$('.dual-listbox__item').each(function(){
  dataId.push($(this).data('id'));
  nHTML.push($(this).text());
});
console.log(dataId);
console.log(nHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="dual-listbox__item" data-id="1">Politieacademie</li>
<li class="dual-listbox__item" data-id="3">IBM</li>
<li class="dual-listbox__item dual-listbox__item--selected" data-id="5">Energias de Portugal</li>