javascript - Not clear about Usage of change() function as described in the example - Jquery -


i read example here change() event, didn't quite follow double use of change() here. docs says explains "attaches change event select gets text each selected option , writes them in div. triggers event initial text draw." please elaborate last line!!

   <html lang="en">         <head>           <meta charset="utf-8">           <title>change demo</title>           <style>           div {             color: red;           }           </style>           <script src="https://code.jquery.com/jquery-1.10.2.js"></script>         </head>         <body>          <select name="sweets" multiple="multiple">           <option>chocolate</option>           <option selected="selected">candy</option>           <option>taffy</option>           <option selected="selected">caramel</option>           <option>fudge</option>           <option>cookie</option>         </select>         <div></div>          <script>         $( "select" )           .change(function () {             var str = "";             $( "select option:selected" ).each(function() {               str += $( ).text() + " ";             });             $( "div" ).text( str );           })           .change();         </script>          </body>     </html> 

$("select") // line selector     .change(function () {  // line starts adding change event handler     var str = "";     $("select option:selected").each(function () {         str += $(this).text() + " ";     });     $("div").text(str); })     .change();// line triggers event handler (from chained selector). 

the same effect had from:

$("select").change(function () {     var str = "";     $("select option:selected").each(function () {         str += $(this).text() + " ";     });     $("div").text(str); }); $("select").change(); 

or this:

$("select")     .change(function () {     var str = "";     $("select option:selected").each(function () {         str += $(this).text() + " ";     });     $("div").text(str); }); $("select").trigger('change'); 

why first uses chaining , not have select (find) element selector multiple times. ensures handler added prior being triggered.

note: event handlers executed when triggered, either manually user or code such manually triggers handler @ point.

note: in jquery, empty .change() trigger , not add new function since there nothing in there in first one.


Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -