Using my code example below, what I would like to do is keep the images in the first 2 list objects, but hide the images in objects 3 and 4.
Removing the image from the 4th object is simple enough, but how can i remove the image from the 3rd object while keeping the image on the 2nd object.
<ul id="list">
<li class="start"><img class="postImage" src="image1.png" /><p>Some text here</p></li>
<li><img class="postImage" src="image2.png" /><p>Some text here</p></li>
<li><img class="postImage" src="image3.png" /><p>Some text here</p></li>
<li class="end"><img class="postImage" src="image4.png" /><p>Some text here</p></li>
开发者_JAVA百科</ul>
Use jQuery's gt()
selector.
To hide the entire li
associated with those images use:
$("#list li:gt(1)").hide ();
To hide just the images use:
$("#list li:gt(1) img").hide ();
See it in action at jsFiddle.
Look at the :nth-child() JQuery selector.
$('#list li img:nth-child(4)').hide();
$('#list li img:nth-child(3)').hide();
// indexing from 1
or:
var imgs = $("#list li img");
imgs.eq(2).hide();
imgs.eq(3).hide();
// indexing from 0
This isn't a very universal form, but does the job in your situation:
$("#list li img").eq(2).hide(); // hides the 3rd img
$("#list li img").eq(3).hide(); // hides the 4th img
A more abstract way, this would hide all img after the 2nd:
$("#list li img").each(function(i) {
if (i > 1) {
$(this).hide();
}
});
Do it with CSS, very simple
ul#list li img:nt-child(3) , ul#list li img:nt-child(4){
display:none;
}
Or the easiest way:
$('#list li:eq(2) img').hide();
精彩评论