: n-of-type () in jQuery / Sizzle?
Das hat mich überraschtBrutzeln (die von jQuery verwendete Auswahlmaschine) ist bereits integriert:nth-child()
Selektor, aber es fehlt ein:nth-of-type()
Wähler.
Um den Unterschied zwischen zu veranschaulichen:nth-child()
und:nth-of-type()
und um das Problem zu veranschaulichen, betrachtendas folgende HTML-Dokument:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>:nth-of-type() in Sizzle/jQuery?</title>
<style>
body p:nth-of-type(2n) { background: red; }
</style>
</head>
<body>
<p>The following CSS is applied to this document:</p>
<pre>body p:nth-of-type(2n) { background: red; }</pre>
<p>This is paragraph #1.</p>
<p>This is paragraph #2. (Should be matched.)</p>
<p>This is paragraph #3.</p>
<p>This is paragraph #4. (Should be matched.)</p>
<div>This is not a paragraph, but a <code>div</code>.</div>
<p>This is paragraph #5.</p>
<p>This is paragraph #6. (Should be matched.)</p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(function() {
// The following should give every second paragraph (those that had red backgrounds already after the CSS was applied) an orange background.
// $('body p:nth-of-type(2n)').css('background', 'orange');
});
</script>
</body>
</html>
Da nutzt Sizzle den Browser nativquerySelector()
undquerySelectorAll()
Methoden, wenn diese vorhanden sind (d. h. in Browsern, die das bereits implementierenSelectors API), Zeug wie$('body p:nth-child');
wird natürlich funktionieren. In älteren Browsern funktioniert dies jedoch nicht, da Sizzle keine Fallback-Methode für diesen Selektor hat.
Ist es möglich, die einfach hinzuzufügen:nth-of-type()
Selektor zu Sizzle, oder um es in jQuery zu implementieren (mitdas eingebaute:nth-child()
Wähler, vielleicht)? EINBenutzerdefinierter Selektor mit Parametern wäre nett.