我正在尝试将变量x插入到现有的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 :(得分: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>
我不确定,但您可能需要添加一些&#39;或&#34;之前和之后的PHP代码
我同意@ sublimeobject的评论
答案 1 :(得分:1)
首先,您希望获得实际的id
和src
:
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>