我有一个动态创建的元素列表,这些元素是特定状态下的作业。每个州可以有多个工作,我正在尝试选择每个州的第一个,但不仅仅是这个巨大的列表中的第一个。例如:
<section class="careers">
<div data-state="career-illinois">...</div>
<div data-state="career-illinois">...</div>
<div data-state="career-illinois">...</div>
<div data-state="career-michigan">...</div>
<div data-state="career-michigan">...</div>
<div data-state="career-michigan">...</div>
<div data-state="career-ohio">...</div>
<div data-state="career-ohio">...</div>
</section>
我想(使用js或css)只选择每个组的第一个状态。 我希望通过以下方式实现这一目标:
.careers div[class*="career-"]:nth-of-type(1) h2 {
color: #636467;
}
但那没用。我尝试了几种方法用jQuery来定位它但没有运气。甚至不确定这是否可能?
答案 0 :(得分:0)
一种方法是遍历div并跟踪你是否已经看过具有该数据属性的div
var jobs = [];
$('section.careers div').each(function () {
if ($.inArray($(this).data('state'), jobs) === -1) { // an element with this data attribute hasn't been encountered yet
jobs.push($(this).data('state')); // Add the data attribute to our tracking array
$(this).addClass('first')
}
})
.first {
color: #636467;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section class="careers">
<div data-state="career-illinois">...</div>
<div data-state="career-illinois">...</div>
<div data-state="career-illinois">...</div>
<div data-state="career-michigan">...</div>
<div data-state="career-michigan">...</div>
<div data-state="career-michigan">...</div>
<div data-state="career-ohio">...</div>
<div data-state="career-ohio">...</div>
</section>
与否: