簡體   English   中英

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>'>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM