繁体   English   中英

如何使用JavaScript更改HTML标记

[英]How to change HTML tags by using JavaScript

我试图将变量x插入到现有的html标记中。

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>

这应该工作

<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的评论

首先,您想获得实际的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;

然后你可以在你的image标签中写下新的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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM