[英]How to change HTML tags by using JavaScript
I am trying to insert the variable x to an existing html-tag. 我试图将变量x插入到现有的html标记中。
The image-tag <img id="Img" src="IMG/.jpg"/>
should get the variable x at the end of its id and its src: image-tag
<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>
this here should work 这应该工作
<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>
im not sure but you may have to add some ' or " befor and after the php code 我不确定,但你可能需要添加一些'或'前后和PHP代码
and i agree with @sublimeobject's comment 我同意@ sublimeobject的评论
First you want to get the actual id
and src
: 首先,您想获得实际的
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;
You wanted to add the variable x to both of them: 您想要将变量x添加到它们中:
var newId = imgId + x;
var newSrc = imgSrc + x;
Then you can write the new id
and the new src
in you image tag: 然后你可以在你的image标签中写下新的
id
和新的src
:
path.setAttribute("id", newId);
path.setAttribute("src", newSrc);
So your whole code should look like 所以你的整个代码应该是这样的
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.