从多个元素的属性构建数组

时间:2018-05-09 09:09:00

标签: jquery

我有这样的HTML:

<li class="select2-selection__choice" title="10" data-select2-id="22">
  <span class="select2-selection__choice__remove" role="presentation">×</span>
   10
</li>

我需要使用此类找到每个liselect2-selection__choice并且我需要title属性的唯一值。可能吗?

我可以拥有很多这些li元素,但它们具有不同的值。我需要数组中的每个值。

2 个答案:

答案 0 :(得分:1)

1.创建一个空的jQuery数组

2.使用.each()

liselect2-selection__choice类的var title_array = []; $('li.select2-selection__choice').each(function(){ title_array.push(parseInt($(this).attr('title'))); }); console.log(title_array); 元素进行迭代

3.使用.attr()获取标题值,然后使用parseInt将其转换为整数,并使用.push()将其推送到数组

这样做: -

$(document).ready(function(){
  var title_array = [];

  $('li.select2-selection__choice').each(function(){
    title_array.push(parseInt($(this).attr('title')));
  });
  console.log(title_array);
});

工作代码段: -

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="select2-selection__choice" title="10" data-select2-id="22">
      <span class="select2-selection__choice__remove" role="presentation">×</span>10
  </li>
  <li class="select2-selection__choice" title="11" data-select2-id="23">
      <span class="select2-selection__choice__remove" role="presentation">×</span>11
  </li>
  <li class="select2-selection__choice" title="12" data-select2-id="24">
    <span class="select2-selection__choice__remove" role="presentation">×</span>12
  </li>
</ul>
&#13;
TIF
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用map(),并考虑在标题上使用trim()。

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="select2-selection__choice" title="
                                        10
                                    " data-select2-id="22"><span class="select2-selection__choice__remove" role="presentation">×</span> 10
</li>
<li class="select2-selection__choice" title="
                                        10
                                    " data-select2-id="22"><span class="select2-selection__choice__remove" role="presentation">×</span> 10
</li>
<li class="select2-selection__choice" title="
                                        10
                                    " data-select2-id="22"><span class="select2-selection__choice__remove" role="presentation">×</span> 10
</li>
&#13;
{{1}}
&#13;
&#13;
&#13;