récupération des balises h2
Bonsoir,
J'ai un contenu html composé de balises h1 et h2, j'aimerais, par jQuery, créer un sommaire avec des ancres qui renvoient vers les titres (h1) et sous-titres (h2), le code fonctionne pour les balises h1, mais les balises h2 ne s'ajoutent pas au sommaire, je ne comprends pas pourquoi... Voici le code:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" >
<head>
<title>Hello World avec jQuery</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<div id="contenu">
<p>
Introduction
</p>
<h1>Chapitre Un</h1>
<div class="chapitre">
<h2>Première partie</h2>
<p>Paragraphes.</p>
<h2>Deuxième partie</h2>
<p>Paragraphes.</p>
</div>
<h1>Chapitre Deux</h1>
<p>Paragraphes.</p>
<h1>Conclusion</h1>
<div class="chapitre">
<h2>Que retenir ?</h2>
<p>Paragraphe.</p>
<h2>Remerciements</h2>
<p>Paragraphe.</p>
</div>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$('#contenu').before('<div id="sommaire"><ol class="niveau1"></ol></div>');
$('#contenu > h1').each(function(i1, titre1)
{
$(titre1).attr('id', 'ancre-'+i1);
$('#sommaire > .niveau1').append('<li id="sommaire-"'+i1+'"><a href="#ancre-'+i1+'">'+$(titre1).text()+'</a></li>');
if ($('#contenu > h1:eq('+i1+') + div.chapitre').length >= 1)
{
alert('toto');
$('#sommaire-'+i1).after('<ol class="niveau2"></ol>');
$('#contenu > h1:eq('+i1+') + div.chapitre > h2').each(function(i2, titre2)
{
$(titre2).attr('id', 'ancre-'+i1+'-'+i2);
$('#sommaire > .niveau1 > .niveau2').append('<li id="sommaire-'+i1+'-'+i2+'"><a href="#ancre'+i1+'-'+i2+'">'+$(titre2).text()+'</a></li>');
});
}
});
</script>
</body>
</html> |
Le ":eq()" empêche l'accès à la condition (le message "toto" n'apparait pas).
Merci pour l'aide !