javascript - jquery display a list of items in <ul> -


hi want display list of item inside

sample html code

<h3 id="game-filter" class="gamesection">            <span>game</span></h3>         <div id="game-filter-div" style="padding: 0;">             <ul id="gamelist">             </ul>         </div> 

code

var games = new array();     games[0] = "world of warcraft";     games[1] = "lord of rings online";     games[2] = "aion";     games[3] = "eve online";     games[4] = "final fantasy xi";     games[5] = "city of heros";     games[6] = "champions online";     games[7] = "dark age of camelot";     games[8] = "warhammer online";     games[9] = "age of conan";     function pageloaded(){         var list = "";              for(i=0; i<games.length; i++){         list ="<li>"+games[i]+"</li>";         $("#gamelist").append(list);         //document.getelementbyid("gamelist").innerhtml=list;         list = "";         }  } 

seems there wrong js code. doesn't output anything

there many things doing wrong in it.

firstly, not pure javascript, jquery.

you need reference jquery api able use jquery.

however, can achieve want through pure javascript also.

now let's @ mistakes

  1. you have created function pageloaded, have not called anywhere. need call function in order make logic work. assuming want call pageloaded method when page ready. can either call on body load or inside jquery's .ready i.e $(document).ready(function(){ pageloaded()});. method ensures, logic executes when dom ready

  2. you have written non-keyword, meaningless words inside method "items in array". remove in order make function work. assuming wanted put comment on there, put comment inside script tag:

     //items in array 
  3. you not concatenating new values list variable, overwritting content each iteration, instead of list ="<li>"+games[i]+"</li>"; this,

     list +="<li>"+games[i]+"</li>"; 
  4. finally, appending list #gamelist inside loop. outside loop. once list complete. , remove line list=" " place line $("#gamelist").append(list); outside loop.

try function this:

var games = new array();     games[0] = "world of warcraft";     games[1] = "lord of rings online";     games[2] = "aion";     games[3] = "eve online";     games[4] = "final fantasy xi";     games[5] = "city of heros";     games[6] = "champions online";     games[7] = "dark age of camelot";     games[8] = "warhammer online";     games[9] = "age of conan"; $(document).ready(function(){         var list = "";         for(i=0; i<games.length; i++){         list +="<li>"+games[i]+"</li>";         }     $("#gamelist").append(list);  }); 

see fiddle


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -