Create functions dynamically

Create functions dynamically

In my site, I am reading from a database, get the total number of elements (line 3) and display chunks of data in div's. But I need to add functions to these div's. The following code is not working, is there an alternate way of achieving this?
Thanks in advance

  1. <script type="text/javascript">
  2.     $("document").ready(function(){
  3.        var total = $("#number_of_elements").val();
  4.        var name_header = "";
  5.        var name_div = "";
  6.        for(var i=1;i<=total;i=i+1){
  7.          name_header = "#top_header" + i;
  8.          name_div = "#top" + i;
  9.          $(name_header).click(function(){
  10.            $(name_div).toggle("slow");
  11.          });
  12.        }
  13.     });
  14. </script>