ZhouW ZhouW - 11 months ago 88
HTML Question

jQuery: using a loop to create many elements with images and html

I have a loop like this:

for (i = 0; i < number; i++) {
// retrieve several pieces of information each time which will be result[0], result[1] etc.
p = document.createElement('p')
p.className = 'box'
p.innerHTML = '<img src="http://website.com/1.png" width="80%" height="100%"</a>' + result[0] + '<h5> more html etc... </h5>'
maintable.appendChild(p)
}


I need the image to change according to the value if
i
(be
website.com/1.png
for
i=0
,
website.com/2.png
for
i=1
etc) and append HTML after that which will include the
result[0]
,
result[1]
etc. that the loop fetches.

I have tried adding an
id
to the image and then doing
('#id').attr('src', 'http://website.com/' + (i + 1) + '.png')
at the end of the loop, but this isn't working as intended. I've also tried using
p.append
for everything I need to add (instead of one
innerHTML
), but this is ignoring HTML eg.
p.append("<h5>Object #1</h5>")
will show the h5 tag on the page.

I have looked at answers for adding multiple images through a loop but haven't got them to work in this specific case.

How should this best be done?

Answer Source

I think your problem is the (i+1). This turns your expression into an integer. Just use i with no math expression. I tried this

p.innerHTML = '<img src="http://hippopool.com/media/'+i+'.jpg" width="600" height="100"><h5>more html etc</h5>';

And don't forget to terminate your javascript lines with semicolon.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download