如何将输入元素动态插入到模态中?
How can I insert an input element dynamically into a modal?
我正在研究用户输入的模式。可用的输入取决于用户点击的 button/case,例如在一种情况下,模态框应该提供文本输入,而在另一种情况下,模态框应该显示一个单选按钮。
因此,我想使用 JavaScript 动态插入模态的输入元素。
在一个简单的 html 页面中测试我的代码有效,但不在模态中。
我错过的模态有什么特别之处吗?如何调整我的代码以获取输入元素?
<html lang="en">
<div id="workModal" class="w3-modal">
<div class="w3-modal-content">
<span class="close">×</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] 而不是输入元素。
您必须使用如下代码在 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>
});
我正在研究用户输入的模式。可用的输入取决于用户点击的 button/case,例如在一种情况下,模态框应该提供文本输入,而在另一种情况下,模态框应该显示一个单选按钮。 因此,我想使用 JavaScript 动态插入模态的输入元素。
在一个简单的 html 页面中测试我的代码有效,但不在模态中。 我错过的模态有什么特别之处吗?如何调整我的代码以获取输入元素?
<html lang="en">
<div id="workModal" class="w3-modal">
<div class="w3-modal-content">
<span class="close">×</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] 而不是输入元素。
您必须使用如下代码在 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>
});