:nth-last-of-type() 选择器
nth-last-of-type selector
描述:选择所有这样的元素,它们是它们的父元素中的倒数第n个子元素,即从最后的元素往前数,相对于具有相同元素名的同辈元素。
加入于: 1.9
jQuery( ":nth-last-of-type(index/even/odd/equation)" )index: 每个要匹配的子元素的索引值,从1开始,也可以是字符串even或odd,或者是一个公式(例如:nth-last-of-type(even)、:nth-last-of-type(4n))
因为:nth-选择器的jQuery编译器严格派生自CSS规范文档,所以n的值是基于1的索引,意味着计数从1开始。对于其它选择器表达式,比如说:eq()或:even,jQuery遵循JavaScript的“0起步索引”计数。给定一个<ul>,它包含了三个<li>,$( 'li:nth-last-type(1)' )选中了第三个<li>,即最后一个<li>。
关于这种用法的进一步讨论,可在W3C CSS specification找到。
示例
在每个匹配的<ul>中查找倒数第二个<li>,并将它标记出来。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>nth-last-of-type demo</title>
<style>
div {
float: left;
}
span {
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>
<ul>
<li>John</li>
<li>Karl</li>
<li>Adam</li>
</ul>
</div>
<div>
<ul>
<li>Dan</li>
</ul>
</div>
<div>
<ul>
<li>Dave</li>
<li>Rick</li>
<li>Timmy</li>
<li>Gibson</li>
</ul>
</div>
<script>
$( "ul li:nth-last-of-type(2)" ).append( "<span> - 2nd to last!</span>" );
</script>
</body>
</html>
演示结果
这是一个游戏场,看看用不同的字符串的选择器是否起作用。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>nth-last-of-type demo</title>
<style>
button {
display: block;
font-size: 12px;
width: 100px;
}
div {
float: left;
margin: 10px;
font-size: 10px;
border: 1px solid black;
}
span {
color: blue;
font-size: 18px;
}
#inner {
color: red;
}
td {
width: 50px;
text-align: center;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>
<button>:nth-last-of-type(even)</button>
<button>:nth-last-of-type(odd)</button>
<button>:nth-last-of-type(3n)</button>
<button>:nth-last-of-type(2)</button>
</div>
<div>
<button>:nth-last-of-type(3n+1)</button>
<button>:nth-last-of-type(3n+2)</button>
</div>
<div>
<table>
<tr><td>John</td></tr>
<tr><td>Karl</td></tr>
<tr><td>Brandon</td></tr>
<tr><td>Benjamin</td></tr>
</table>
</div>
<div>
<table>
<tr><td>Sam</td></tr>
</table>
</div>
<div>
<table>
<tr><td>Glen</td></tr>
<tr><td>Tane</td></tr>
<tr><td>Ralph</td></tr>
<tr><td>David</td></tr>
<tr><td>Mike</td></tr>
<tr><td>Dan</td></tr>
</table>
</div>
<span>tr<span id="inner"></span></span>
<script>
$( "button" ).click(function() {
var str = $( this ).text();
$( "tr" ).css( "background", "white" );
$( "tr" + str ).css( "background", "#ff0000" );
$( "#inner" ).text( str );
});
</script>
</body>
</html>
演示结果