How to make same javascript code work on more than one same kind of field?
Hmmm, this is a kind of tricky one! Because you want the element corresponding to the button you clicked to be the only one that toggles, correct? Not all of the elements?

I think you want something like this for your code, where everything between [] is replaced with the relevant selector. So [BUTTON CLASS] would become the class that you apply to all the buttons, such as "button", not the ID that only gets applied to a single button ("button1", "button2", and so on). Likewise, [CHILD CLASS] would be replaced with a class that you apply to all elements that you have IDs such as "p1", "p2", etc on.

(function ($) {
  Drupal.behaviors.myfunction = {
    attach: function(context, settings) {
      $( ".[BUTTON CLASS]" ).each(function (index) {
        $(this).click(function() {
          $(this).parent().children(".[CHILD CLASS]").toggle("slow");
        });
      });
    }
  }
})(jQuery);


Hope that helps!

Edit
Updates made to the code to get the button parent and then the #p1 from there. It assumes that the #p1 and the #button1 are both children of the same element.

Edit 2
Given the structure

&lt;div class="buttoncontainer"&gt;
  &lt;ul class="buttonlist"&gt;
    &lt;li&gt;&lt;button class="button1"&gt;Toggle&lt;/button&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="#"&gt;&lt;button class="button2"&gt;Link&lt;/button&gt;&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;
  &lt;p class="p1" style="display:none"&gt;Text to be written here&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;div class="buttoncontainer"&gt;
  &lt;ul class="buttonlist"&gt;
    &lt;li&gt;&lt;button class="button1"&gt;Toggle&lt;/button&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="#"&gt;&lt;button class="button2"&gt;Link&lt;/button&gt;&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;
  &lt;p class="p1" style="display:none"&gt;Text to be written here&lt;/p&gt;
&lt;/div&gt;
&lt;hr&gt;
&lt;div class="buttoncontainer"&gt;
  &lt;ul class="buttonlist"&gt;
    &lt;li&gt;&lt;button class="button1"&gt;Toggle&lt;/button&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="#"&gt;&lt;button class="button2"&gt;Link&lt;/button&gt;&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;
  &lt;p class="p1" style="display:none"&gt;Text to be written here&lt;/p&gt;
&lt;/div&gt;


The following JS does what you want, I believe:

$( ".button1" ).each(function (index) {
  $(this).click(function() {
    $(this).parents('.buttoncontainer').children(".p1").toggle("slow");
  });
});