javascript 单击按钮并在 div 中创建图像

javascript click a button and create an image in a div

我搜索了我的这个问题并找到了一些解决方案,但我一定是做错了什么,因为它不起作用。 我想,简单地说,只需按下一个按钮,让图像出现在某个 div 中。稍后,我想添加更多按钮,每个按钮将对应一个图像以相同的方式更改此图像div。

我的代码是这样的:

<!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    
 </style>    
</head>
<body>
 <button id="button1">Button 1</button><button id="button2">Button 2</button></br>
 <button id="button3">Button 3</button><button id="button4">Button 2</button></br>
 <p> </p>
 
 <div id="1"></div>
 <div id="2"></div>
 
 
 <script type="text/javascript">
  document.getElementById("button1").onclick=function() {
   document.getElementById("1").appendChild="<img id="image1" src="img/image1.png" />;
  }
  document.getElementById("button2").onclick=function() {
   document.getElementById("1").appendChild="<img id="image2" src="img/image2.png" />;
  }
  document.getElementById("button3").onclick=function() {
   document.getElementById("2").appendChild="<img id="image3" src="img/image3.png" />;
  }
  document.getElementById("button2").onclick=function() {
   document.getElementById("2").appendChild="<img id="image4" src="img/image4.png" />;
  }
  
 </script> 
</body>
</html>

但不知何故我无法完成这项工作。

您在用双引号封装的字符串中使用了双引号:

"<img id="image1" src="img/image1.png" />;

这需要

"<img id=\"image1\" src=\"img/image1.png\" />";

由于 JavaScript 使用引号(单引号或双引号)设置字符串,您需要使用 \ 转义字符串中的引号以避免破坏字符串。在您的原始代码中 JavaScript 正在解析字符串,在 id= 处找到字符串的末尾并中断,因为它需要行终止符 ;+.

查看第一个和第二个代码块中的突出显示。第二个全是红色,表示正确的转义字符串。

还有

appendChild 仅适用于 nodes/elements 而不适用于字符串。您需要 innerHTML,但是每次都会覆盖 div 的内容。如果你不想这样,你可以使用:insertAdjacentHTML()

示例:

document.getElementById("1").insertAdjacentHTML("beforeend", "<img id=\"image1\" src=\"img/image1.png\" />");

试试这个:

Javascript:
document.getElementById(<img id>).src = "<link to img>";
HTML:
<img id='<img id>' src='<link to img>'>