是否可以为Selector多结果快速获取[..]
属性数组?示例:此处我需要为所有匹配的data-id
快速获取"starts with 'NORMAL'"
个属性数组。但是下面的天真声明当然不起作用。
$('li[data-id^="NORMAL"]').attr('data-id');
var normals = $('li[data-id^="NORMAL"]');
console.log(normals.length);
var normalIDs = $('li[data-id^="NORMAL"]').attr('data-id');
// Need an array containing strings:
// ["NORMAL-ev1", "NORMAL-ev2", "NORMAL-ev4"]
console.log(normalIDs.length);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li data-id="NORMAL-ev1" data-start="12:30am" data-end="1:00am"> TEST1 </li>
<li data-id="NORMAL-ev2" data-start="12:45am" data-end="1:15am"> TEST2 </li>
<li data-id="SPECIAL-ev3" data-start="3:30am" data-end="3:45am"> SPECIAL TEST3 </li>
<li data-id="NORMAL-ev4" data-start="3:30am" data-end="3:45am"> TEST4 </li>
&#13;
答案 0 :(得分:1)
你真的需要循环,但你可以使用$.each()
:
var normals = $('li[data-id^="NORMAL"]');
var normalIDs = [];
$('li[data-id^="NORMAL"]').each(function () {
normalIDs.push($(this).attr('data-id'));
});
// Need an array containing strings:
// ["NORMAL-ev1", "NORMAL-ev2", "NORMAL-ev4"]
console.log(normalIDs.length);
console.log(normalIDs);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li data-id="NORMAL-ev1" data-start="12:30am" data-end="1:00am"> TEST1 </li>
<li data-id="NORMAL-ev2" data-start="12:45am" data-end="1:15am"> TEST2 </li>
<li data-id="SPECIAL-ev3" data-start="3:30am" data-end="3:45am"> SPECIAL TEST3 </li>
<li data-id="NORMAL-ev4" data-start="3:30am" data-end="3:45am"> TEST4 </li>
&#13;
发生了什么是选择器获取最后找到的元素并返回data-id
的内容。
答案 1 :(得分:1)
可以使用map()
根据元素特定的返回值
var normalIDs = $('li[data-id^="NORMAL"]').map(function() {
return $(this).data('id');
}).get();
console.log(normalIDs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-id="NORMAL-ev1" data-start="12:30am" data-end="1:00am"> TEST1 </li>
<li data-id="NORMAL-ev2" data-start="12:45am" data-end="1:15am"> TEST2 </li>
<li data-id="SPECIAL-ev3" data-start="3:30am" data-end="3:45am"> SPECIAL TEST3 </li>
<li data-id="NORMAL-ev4" data-start="3:30am" data-end="3:45am"> TEST4 </li>
</ul>