jquery - How to populate unordered list from array with javascript? -


i'm creating app phonegap. want loop through form of array create unordered list format url , title stored values:

<li><a href="[url]">[title]</a></li> 

i'm bit new way of developing apps, , i'm not sure best way store data in root of app. guess could've made js array, want keep saved in seperate file. therefore made json file:

{   "title": "thisistheurl.com",   "title": "thisistheurl.com" } 

how able create list based on data local json file? tried 1 without luck:

$.getjson( "links.json", function( data ) {                   var items = [];                   $.each( data, function( key, val ) {                     $("linklist").append( "<li id='" + key + "'>" + val + "</li>" );                   }); }); 

two things need change in:

   $.each( data, function( key, val ) {                     $("linklist").append( "<li id='" + key + "'>" + val + "</li>" );                   }); 

at first, there no element called linklist, may wanted append elements in ul class .linklist or id #linklist.

another one, inside $.each key represents title , value represents the url. have assigned wrongly.

      $("linklist").append( "<li id='" + key + "'>" + val + "</li>" ); 

it should be

      $("selector").append( "<li id='" + val+ "'>" + key+ "</li>" ); 

and dont see a tag here. may need add a tag well.

also note can't have duplicate keys title in object. in case may need go array of objects.

[{   "title": "title desire",   "link" : "thisistheurl.com" },{   "title": "title desire",   "link" : "thisistheurl.com" },{   "title": "title desire",   "link" : "thisistheurl.com" }] 

demo:

     var data = [{    "title": "title desire",    "link" : "thisistheurl.com"  },{    "title": "title desire",    "link" : "thisistheurl.com"  },{    "title": "title desire",    "link" : "thisistheurl.com"  }];       $.each( data, function( key, val ) {   var $li = $("<li><a href='"+val.link+"'>"+val.title+"</a></li>");         $("#linklist").append($li);               });
ul#linklist  {  border: 1px solid black;    }  #linklist li a:link {     color: red;  }
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>  <ul id="linklist"></ul>    


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -