我有这样的HTML:
<li class="select2-selection__choice" title="10" data-select2-id="22">
<span class="select2-selection__choice__remove" role="presentation">×</span>
10
</li>
我需要使用此类找到每个li
:select2-selection__choice
并且我需要title
属性的唯一值。可能吗?
我可以拥有很多这些li
元素,但它们具有不同的值。我需要数组中的每个值。
答案 0 :(得分:1)
1.创建一个空的jQuery数组
2.使用.each()
对li
个select2-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);
});
工作代码段: -
<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;
答案 1 :(得分:0)
使用map(),并考虑在标题上使用trim()。
<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;