2014-05-16 63 views
0

我試圖將變量x插入到現有的html標記中。如何使用JavaScript更改HTML標記

圖像標籤<img id="Img" src="IMG/.jpg"/>應在其ID和SRC年底得到變量x:

 <script> 
      var images = <?php echo (json_encode($files));?> 
      for(x = 1;x < $images.length-2;x++){ 
       // <img id="Img"+x src="IMG/"+x+.jpg"/> 
      } 
     </script> 
+0

您似乎錯過了腳本標記的重要性,HTML不會像PHP中一樣被回顯出來,您必須將它放在某處(並添加引號)。和'images!= $ images'等等 – adeneo

+3

爲什麼不直接用php寫這個? – thesublimeobject

+0

我一直在試圖找到一個重複的東西來用來關閉這個東西,但是每個嘗試類似東西的人都做了(非常非常少的)研究,需要找到一種技術來生成HTML,然後只有特定的問題。 – Quentin

回答

1

首先要得到實際的idsrc

var path = document.getElementsByTagName("img")[0]; // That looks for all img-tags in your document and returns an array with all of them. I took the first one (number 0 in the array) - if it is not the first image, change that number. 
var imgId = path.id; 
var imgSrc = path.src; 

您想添加變量x他們兩個:

var newId = imgId + x; 
var newSrc = imgSrc + x; 

然後,你可以寫新id和新src在你的圖像標籤:

path.setAttribute("id", newId); 
path.setAttribute("src", newSrc); 

所以,你的整個代碼看起來應該像

<script> 
    var images = <?php echo (json_encode($files));?> 
    for(x = 1;x < $images.length-2;x++){ 
     //read the id and src 
     var path = document.getElementsByTagName("img")[0]; 
     var imgId = path.id; 
     var imgSrc = path.src; 

     //change them 
     var newId = imgId + x; 
     var newSrc = imgSrc + x; 

     //and write the new id and new src in the image-tag 
     path.setAttribute("id", newId); 
     path.setAttribute("src", newSrc); 
    } 
</script> 
1

這個位置應該工作

<script> 
     var images = <?php echo (json_encode($files));?>; 
     for(x = 1;x < images.length-2;i++){ 
      document.write('<img id="Img"'+ x + ' src="IMG/"' + x + '.jpg"/>'); 
     } 
</script> 

林不知道,但你可能要在php代碼後添加一些'或者'以及後面的代碼

我同意@ sublimeobject的評論