最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript to loopincrement html code with values up to 55 - Stack Overflow

programmeradmin6浏览0评论

I need to create a list of links in a static (.html) page automatically, is there a way of doing this using JavaScript. I tired a few scripts but couldn't work it out.

this is my html...

<a href="1.html"><img src="images/1.jpg" width="119" height="121" alt="" /></a>

and this is what i want the script to generate 55 times...

<a href="1.html"><img src="images/1.jpg" width="119" height="121" alt="" /></a>
<a href="2.html"><img src="images/2.jpg" width="119" height="121" alt="" /></a>
<a href="3.html"><img src="images/3.jpg" width="119" height="121" alt="" /></a>

... and so on, call me lazy but any help would be most appreciated :)

I need to create a list of links in a static (.html) page automatically, is there a way of doing this using JavaScript. I tired a few scripts but couldn't work it out.

this is my html...

<a href="1.html"><img src="images/1.jpg" width="119" height="121" alt="" /></a>

and this is what i want the script to generate 55 times...

<a href="1.html"><img src="images/1.jpg" width="119" height="121" alt="" /></a>
<a href="2.html"><img src="images/2.jpg" width="119" height="121" alt="" /></a>
<a href="3.html"><img src="images/3.jpg" width="119" height="121" alt="" /></a>

... and so on, call me lazy but any help would be most appreciated :)

Share Improve this question asked May 14, 2013 at 23:21 AmeseyAmesey 8522 gold badges18 silver badges35 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

This should do the trick:

<div id="links">
</div>

<script>
var strLinks = '';

for (var i = 1; i <= 55; i++) {
    strLinks += '<a href="'+ i +'.html"><img src="images/'+ i +'.jpg" width="119" height="121" alt="" /></a>';
}

document.getElementById("links").innerHTML = strLinks;
</script>

JS Fiddle example: http://jsfiddle/RWUdG/2/

EDIT: Oops, missed a quote. Fixed.

This could also work.

<div id="imgs">
</div>

<script>
var i = 55; while (i--) {document.getElementById("imgs").innerHTML += '<a href='+ i +'.html"><img src="images/'+ i +'.jpg" width="119" height="121" alt="" /></a>';}
</script>

http://jsfiddle/T2c3G/

If your anchor tags are contained inside a div, you can do this:

$(document).ready(function(){
var linksHtml = "";
for(var i = 1; i <= 55; i++){
    linksHtml += '<a href="'+(i)+'.html"><img src="images/'+(i)+'.jpg" width="119" height="121" alt="" /></a>';
}
$("#linksDiv").html(linksHtml);
});
发布评论

评论列表(0)

  1. 暂无评论