javascript - Append link to href from JSON -
can explain me how can append link
json file a href
? grab images have no idea how links.
this code using
<body style="background: #e5e5e5"> <div class="container"> <div class="row"> <div class="col-sm-4"> <a href=""> <div class="cover" id="img"></div> </a> </div> </div> </div> <script> var data = { "info": [{ "cover": "highlighted/1.gif", "link":"http://google.com" }, { "cover": "highlighted/1.gif", "link":"http://google.com" }] }; data.info.foreach( function(obj) { var img = new image(); img.src = obj.cover; document.getelementbyid("img").appendchild(img); }); </script> </body>
note: <a>
inline element, should put in div.
here working code:
<body style="background: #e5e5e5"> <div class="container"> <div class="row"> <div class="col-sm-4"> <div class="cover" id="img"> </div> </div> </div> </div> <script> var data = { "info": [{ "cover": "highlighted/1.gif", "link":"http://google.com/1" }, { "cover": "highlighted/2.gif", "link":"http://google.com/2" }] }; var imagesblock = document.getelementbyid("img"); data.info.foreach( function(obj) { var img = new image(); img.src = obj.cover; var = document.createelement('a'); a.setattribute('href', obj.link); a.appendchild(img); imagesblock.appendchild(a); }); </script> </body>
here version, clone dom tree instead,, following discussion (see below):
<body style="background: #e5e5e5"> <div class="container"> <div class="row" id="repeatingimages"> <div class="col-sm-4"> <div class="cover"> <a><img /></a> </div> </div> </div> </div> <script> var data = { "info": [{ "cover": "highlighted/1.gif", "link":"http://google.com/1" }, { "cover": "highlighted/2.gif", "link":"http://google.com/2" }] }; var repeatingimages = document.getelementbyid("repeatingimages"); // template block, clone , remove source var blocktemplate = repeatingimages.getelementsbytagname("div")[0].clonenode(true); repeatingimages.getelementsbytagname("div")[0].remove(); data.info.foreach( function(obj) { block = blocktemplate.clonenode(true); block.getelementsbytagname("a")[0].setattribute('href', obj.link); block.getelementsbytagname("img")[0].setattribute('src', obj.cover); repeatingimages.appendchild(block); }); </script> </body>
Comments
Post a Comment