2014-12-06 5 views
-1

i have an retrieved array items in the var test,как разместить массив [i] элементов в <img src=""> и <a href=""> tags

for example :

var test = img; 

Where test[0] holds the value that is grabbed from database as /images/gallery/1.jpp

Now i need to place the var test[0] to be place within img src="" and a href="", so how can i achieve this?

+0

Как это 'img' является как массивом, так и элементом? Ваше описание данных для меня непонятно. Если 'img src =" "' ссылается на другой идентификатор 'img', то является ли он элементом в DOM? Или строка? –

ответ

1

Assign a value to the property "id" of your img and play with its attributes.

<img src="" id="image_id_here" width="300" height="400"> 
<script>document.getElementById('image_id_here').setAttribute('src', test[0]);</script> 

Assumptions made:

  • "test" is an array of strings
  • You demand working through a client-sided scripting language such as Javascript to perform front-end operations.
+0

Ваше второе решение не сработает. Вы разместили JavaScript до того, как изображение было загружено на страницу. Поэтому 'document.getElementById ('image_id_here')' не будет определен. – putvande

0

you need a div tag with the id of container:

<div id="container"></div> 

You can then use javascript to iterate over the list:

var imgs = ""; 

    for (var i = 0; i < test.length; i++) { 
     var img = document.createElement('img'); 
     img.setAttribute('src', test[i]); 
     imgs += img.outerHTML; 
    } 

    var container = document.getElementById('container'); 
    container.innerHTML = imgs; 

See plunker