【问题标题】:Insert Image to div upon click单击时将图像插入到 div
【发布时间】:2018-11-28 23:17:05
【问题描述】:

单击按钮并选中复选框后,我希望能够将图像添加到此 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);

【问题讨论】:

    标签: javascript html innerhtml appendchild createelement


    【解决方案1】:

    您说您尝试使用 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>

    【讨论】:

    • 谢谢!这也对我有用。我不知道我最初做错了什么。
    • 我很高兴它对你有用!你觉得将此答案标记为正确吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多