首页 > 解决方案 > 单击时将图像插入到 div

问题描述

单击按钮并选中复选框后,我希望能够向此 div 添加图像。我已经确认复选框部分可以正常工作,但无法让照片进入 div。

这是我目前拥有的:

<button id="show_button">Show System</button>
<div class="box" id="AC1"></div>
<script>
var show_button = document.getElementById('show_button');
var show = function() {
    // AC Relevant Components;
    var ch_mGT = document.getElementById('mGT').checked;
    // Set AC1
    if (ch_mGT) {
         var AC1_html = "<img src='http://localhost/....png' alt='Micro Turbine' 
         height='50px'>";
         document.getElementById("AC1").innerHTML(AC1_html);
    }
}
show_button.addEventListener("click",show);
</script>

我也已经尝试过:

var AC1_img = document.createElement("img");
AC1_img.src = 'http://localhost/....png'
document.getElementById('AC1').appendChild(AC1_img);

标签: javascripthtmlinnerhtmlappendchildcreateelement

解决方案


您说您尝试使用 appendElement,但它似乎在下面的示例中有效。

var show_button = document.getElementById('show_button');
var show = function() {
 var ch_mGT = document.getElementById('mGT').checked;
 var AC1_img = document.createElement('img')
     AC1_img.src="https://i.ytimg.com/vi/r4Hve6fZ7ik/maxresdefault.jpg"
     AC1_img.style.height = "50px"
     AC1_img.alt = 'Micro Turbine'
	 if (ch_mGT) {
	   document.getElementById("AC1").appendChild(AC1_img)
   }
}
show_button.addEventListener("click",show);
<div class="box" id="AC1"></div>
<input type="checkbox" id="mGT">
<button id="show_button">Show System</button>


推荐阅读