我有一个元素列表如下:
var locationSlug = "paris";
$('div a.country-item.' + locationSlug).slice(0, 3).show();
.country-item { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<a class="country-item paris london">Text1</a>
<a class="country-item tokyo london">Text2</a>
<a class="country-item paris moscow">Text3</a>
<a class="country-item berlin london">Text4</a>
<a class="country-item paris madrid">Text5</a>
<a class="country-item barcelona edinburgh">Text6</a>
<a class="country-item nice dublin">Text7</a>
<a class="country-item paris stockholm">Text8</a>
</div>
我正在尝试显示具有.paris
类的元素的前3个实例,因此不是前3个子元素,因为列表将会很长。我尝试了以下选择器
$('div a.country-item.' + locationSlug).slice(0, 3).show();
但这种切片方法似乎根本不起作用。
对此有任何建议将不胜感激!
答案 0 :(得分:3)
使用jQuery :lt() selector
var locationSlug="paris";
$('div.parent a.'+locationSlug+':lt(3)').show();
http://api.jquery.com/lt-selector/
$(document).ready(function() {
$("div > a").hide();
var locationSlug="paris";
$('div.parent a.'+locationSlug+':lt(3)').show();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<a class="country-item paris london">paris1</a>
<a class="country-item tokyo london">Text</a>
<a class="country-item paris moscow">paris2</a>
<a class="country-item berlin london">Text</a>
<a class="country-item paris madrid">paris3</a>
<a class="country-item barcelona edinburgh">Text</a>
<a class="country-item nice dublin">Text</a>
<a class="country-item paris stockholm">paris4</a>
</div>
&#13;