如何在使用 document.getElementById 时在图像 src 中写入变量的内容?

问题描述 投票:0回答:2

我有以下代码

document.write("<img src=./", i, ".png width='100px' height='100px'>");
document.write("<img src=./", x, ".png width='100px' height='100px'>");
document.write("<img src=./", y, ".png width='100px' height='100px'>");`

并且我想在

src
中使用
getElementById(myImg).InnerHTML

我试过这个

document.getElementById("myImg").innerHTML.src = "./", i, ".png width='100px' height='100px'>";

但是它不起作用

正确的写法是什么?

javascript getelementbyid
2个回答
0
投票

更改

src
,而不是
InnerHTML.src
。您可以在这个问题中看到答案。 并且您需要设置
width
height
的 style

document.getElementById("myImg").src=`./${i}.png`;
document.getElementById("myImg").style.width="100px";
document.getElementById("myImg").style.height="100px";

0
投票

您的代码中有语法错误。

试试这个

const img = document.getElementById("myImg");
const i = 'some_string_or_number'
 
img.src = "./"+i+".png";
img.width='100px';
img.height='100px';
© www.soinside.com 2019 - 2024. All rights reserved.