Addressing first/last item in an ul, li
How do you check whether a DOM element being clicked is either the 'first' li element or the 'l开发者_运维百科ast' li element in an unordered list item??
Based on your question as it appeared before your edit, as well as your comments, it seems you're responding to a li img
being clicked, and trying to find out if that containing li
is the first or last child.
Use .is()
together with .closest()
to check:
$('ul li img').click(function() {
var $li = $(this).closest('li');
if ($li.is(':first-child')) {
// First
} else if ($li.is(':last-child')) {
// Last
}
});
try this:
<ul class="myUnorderedList"><li>First</li><li>Last</li></ul>
js:
$('.myUnorderedList li').click(function(){
if($(this).is(':first')) console.log('first li');
if($(this).is(':last')) console.log('last li');
})
Use first() and last():
$('#ulid > li').first();
$('#ulid > li').last();
If this is your code:
<ul class="myUnorderedList"><li>First</li><li>Last</li></ul>
Then you can access it by the First selector (http://api.jquery.com/first-selector/) or last selector (enter link description here) as follows:
<script>$(".myUnorderedList>li:first").css("font-style", "italic");</script>
<script>$(".myUnorderedList>li:last").css("font-style", "italic");</script>
Maybe this could help
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
With this jquery code
$("li").click(function(){
if ($("li:first").text() == $(this).text() ){
alert("first");
}
if ($("li:last").text() == $(this).text() ){
alert("last");
}
});
See it on http://jsfiddle.net/GT7Mm/
精彩评论