首页 > 解决方案 > 如何将输入元素动态插入到模态中?

问题描述

我正在研究用户输入的模式。可用输入取决于用户单击的按钮/案例,例如,在一种情况下,模式应提供文本输入,在另一种情况下,模式应显示单选按钮。因此,我想用 JavaScript 动态插入我的模式的输入元素。

在一个简单的 html 页面中测试我的代码有效,但不在模式中。我错过的模态有什么特别之处吗?如何调整我的代码以获取输入元素?

<html lang="en">
<div id="workModal" class="w3-modal">
  <div class="w3-modal-content">
  <span class="close">&times;</span>
  <h4>Input</h4>
  <div id="mod_in"></div>
  </div>
</div>
</html>

<script>
var modal = document.getElementById("workModal");
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {modal.style.display = "none";};
window.onclick = function(event) {if (event.target == modal {modal.style.display = "none";}}

// here starts the filling of the modal:
function build_modal(info) {
    let element = document.getElementById("mod_in");
    let inElement = "";
    info.dataInputs.forEach(function (item){
        inElement = document.createElement("input");
        if (item.dataType.includes('string')){
            inElement.setAttribute("type", "text");
        }
        if (item.minOccurs > 0) {inElement.required = true}
        element.appendChild(inElement)
    });
    element.innerHTML = inElement;
    let modal = document.getElementById("workModal");
    modal.style.display = "block";
}
</script>

我的 html 代码中没有输入元素,而是得到一个 [object HTMLInputElement]。

标签: javascripthtmlmodal-dialoguser-input

解决方案


您必须使用如下代码在 html 中附加新元素:

$("button").click(function(){      //you can call your function after any events
  $("p").append("<b>Appended text</b>");  //you can append every element instead of <b> 
});

推荐阅读