Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4

Thread: function return

  1. #1
    New Coder
    Join Date
    Aug 2010
    Location
    myeik
    Posts
    81
    Thanks
    6
    Thanked 5 Times in 5 Posts

    Unhappy function return

    hi,i don't understand about the jquery basic example
    the code is below
    PHP Code:
    <html>
    <
    head>
    <
    script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
      $("button").click(function(){
        $('p').addClass(function(n){
          return 'par_' + n;
        });
      });
    });
    </script>
    <style type="text/css">
    .par_0
    {
    color:blue;
    }
    .par_1
    {
    color:red;
    }
    </style>
    </head>

    <body>
    <h1>This is a heading</h1>
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
    <button>Add classes to p elements</button>
    </body>
    </html> 
    i want to understand about the how is work function(n){ in the function a
    and how work return function return 'par_' + n;
    thanks mate

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    This is one of the possible ways to use the addClass method: The first parameter of the function "n" is the index of the current element out of the jQuery element list

    Let's say you have 10 <p> paragraphs on your page. Then the selector $('p') will result in a list of those paragraphs. addClass(function(n) {...}) will then add a class to each paragraph containing the text par_n. So the first paragraph will have a new class="par_0"

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,371
    Thanks
    11
    Thanked 591 Times in 572 Posts
    i guess mopst methods map to .map(), which i didn't know.
    so, the long-hand would be:

    Code:
     $('p').map(function(n, elm){
          $(elm).addClass('par_' + n);
        });
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #4
    New Coder
    Join Date
    Aug 2010
    Location
    myeik
    Posts
    81
    Thanks
    6
    Thanked 5 Times in 5 Posts
    thanks for explain my dearly friend,


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •