2014-05-16 65 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的评论