2014-12-06 59 views
-1

i have an retrieved array items in the var test,如何在<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

中放置一個數組[i]項目?img'既是數組也是元素?您對數據的描述對我來說還不清楚。如果'img src =「」'指的是不同的'img'標識符,那麼它是否是DOM中的一個元素?或者一個字符串? – 2014-12-06 17:19:06

回答

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 2014-12-06 17:31:28

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

相關問題