问题
In jQuery there are a few colon selectors like
:prev, :next, :last
My question is:
- Are they truly part of jQuery, because they are actually used on DOM elements?
- We seem to have equivalent methods as well in jQuery
prev()
,next()
,last()
. What is the purpose of having 2 different ways?
Any basic examples would be really great.
回答1:
jQuery does not have :prev
or :next
selectors, I have no idea where you came across them. There is a :last
selector, though, as well as :first
, provided by the Sizzle selector library, used by jQuery. It is a non-standard selector, not part of CSS, and is thus implemented in JavaScript.
One purpose of the :last
selector over the .last()
method is so you can use it to filter elements in the middle of a selector sequence, like this (note that :last
and :last-child
are not the same):
$('.a > .b:last > .c')
Rather than having to write a chain of methods like this:
$('.a').children('.b').last().children('.c');
By the way, the "colon selectors" you refer to are called pseudo-classes (colloquially but incorrectly known as "pseudo-selectors").
回答2:
Here is how I made a slider with all sorts of selectors and traversing of objects.
$('#next').click(function () {
if (!$('*').is(':animated')) {
if ($('div.display:visible').is(':nth-child(3)')) {
$('div.display:visible').fadeOut();
$('div.display:first').fadeIn(function () {
$(this).children().fadeIn();
});
} else {
$('div.display:visible').fadeOut().next().fadeIn(function () {
$(this).children().fadeIn();
});
}
}
});
$('#prev').click(function () {
if (!$('*').is(':animated')) {
if ($('div.display:visible').is(':nth-child(1)')) {
$('div.display:visible').fadeOut();
$('div.display:last').fadeIn(function () {
$(this).children().fadeIn();
});
} else {
$('div.display:visible').fadeOut().prev().fadeIn(function () {
$(this).children().fadeIn();
});
}
}
});
回答3:
- yes, they are in the documentation
- sometimes you can't always include everything in the selector or want a subdivision of the selector.
e.g.
$(".mylist").each(function(){
$(this).css("color","red");
$(this).next().show();
})
回答4:
The colon represents a filter like to get the selected option in a dropdown I would use $("select option:selected")
or to get a checked radio box I would use $("input[type=radio]:checked");
There are no :prev and :next filters, but you can find a full list of filters here http://api.jquery.com/category/selectors/
来源:https://stackoverflow.com/questions/6974760/jquery-colon-selectors