How can i extend this script with numbering?
Hi all,
i am using the folowing jquery function to generate a table of contents from the h tags in my web page. I could make some changes but i am not able to extend the function, so that it puts numbers in front of my toc elements like
1.
2.
2.1
2.1.1
2.2.
2.2.1
2.2.4.5
etc....
Can someone help me to extend this function with this numbering?
-
<script type="text/javascript">
(function($) {
$.toc = function(tocList) {
$(tocList).addClass('jquery-toc');
var tocListArray = tocList.split(',');
$.each(tocListArray, function(i,v) { tocListArray[i] = $.trim(v); });
var $elements = $('.jquery-toc');
$('body').append('<div></div>');
var $toc = $('body div:last');
var lastLevel = 1;
$toc.append('<ul class="jquery-toc-1"></ul>');
$elements.each(function() {
var $e = $(this);
var text = $e.text();
var anchor = text.replace(/ /g,'-');
$e.before('<a name="' + anchor + '"></a>');
var level;
$.each(tocListArray, function(i,v) {
if (v.match(' ')) {
var vArray = v.split(' ');
var e = vArray[vArray.length - 1];
} else { e = v; }
if ($e.is(e)) { level = i+1; }
});
var className = 'jquery-toc-' + level;
var li = '<li><a href="#' + anchor + '">'+ level + ' ' + text +'</a></li>';
$e.prepend(level + " ");
if (level == lastLevel) {
$('ul.' + className + ':last',$toc).append(li);
} else if (level > lastLevel) {
var parentLevel = level - 1;
var parentClassName = 'jquery-toc-' + parentLevel;
$('ul.' + parentClassName + ':last',$toc).
append('<ul class="' + className + '"></ul>');
$('ul.' + className + ':last',$toc).append(li);
} else if (level < lastLevel) {
$('ul.' + className + ':last',$toc).append(li);
}
lastLevel = level;
});
var $toc_ul = $('ul.jquery-toc-1',$toc);
$toc.remove();
return($toc_ul);
}
})(jQuery);
$(document).ready(function(){
$.toc('#pagecontent_b h1,#pagecontent_b h2,#pagecontent_b h3').prependTo('#pagecontent_b');
});
</script>
regards
bc