如何将输入元素动态插入到模态中?

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


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


<html>

<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] 而不是 input 元素。


慕容森
浏览 105回答 1
1回答

慕丝7291255

您必须使用如下代码在 html 中添加新元素:$("button").click(function(){&nbsp; &nbsp; &nbsp; //you can call your function after any events&nbsp; $("p").append("<b>Appended text</b>");&nbsp; //you can append every element instead of <b>&nbsp;});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript