Home  >  Article  >  Web Front-end  >  Detailed explanation of four solutions to obtain the first li positioning of jq ul

Detailed explanation of four solutions to obtain the first li positioning of jq ul

高洛峰
高洛峰Original
2017-01-04 14:23:401624browse

If we just get the first li in a ul, then we can write like this:

$("ul li:first");
$("ul li"). eq(0);
$("ul li").first();
$("ul li").slice(0,1);//The first parameter of slice represents the start of selection Position, the second parameter is the ending position

<ul>
<li>安哲</li>
<li>安哲</li>
<li>安哲</li>
<li>安哲</li>
</ul>
<ul>
<li>安哲</li>
<li>安哲</li>
<li>安哲</li>
<li>安哲</li>
</ul>
<ul>
<li>安哲</li>
<li>安哲</li>
<li>安哲</li>
<li>安哲</li>
</ul>
<ul>
<li>安哲</li>
<li>安哲</li>
<li>安哲</li>
<li>安哲</li>
</ul>

I have probably written four solutions

<script type="text/javascript">
//方案一
$(function(){
var list=$("ul");
for (var i = 0; i < list.length; i++) {
$("ul:eq("+i+") li:first").css("background","red");
 
}
});
//方案二
/*$(function(){
$("ul").each(function(){
$(this).children().first().css("background","red"); 
});
});*/
//方案三
/*$(function(){
$("ul li:nth-child(1)").css("background","red");
});*/
//方案四
/*$(function(){
$("ul li:first-child").css("background","red");
});*/
</script>

The above is the entire content of this article, I hope it will be helpful to everyone Help, thank you for your support of PHP Chinese website!

For more detailed explanations, please pay attention to the PHP Chinese website for related articles on obtaining the four solutions for jq ul's first li positioning!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn