javascript - 如何将输入元素动态插入到模态中?
问题描述
我正在研究用户输入的模式。可用输入取决于用户单击的按钮/案例,例如,在一种情况下,模式应提供文本输入,在另一种情况下,模式应显示单选按钮。因此,我想用 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>
});
推荐阅读
- c++ - 奇怪的不完整类型不允许错误
- typo3 - 图像宽度取决于 colPos (TYPO3 fluid_styled_content)
- ajax - 在codeigniter中通过ajax更新进度条
- marklogic - 结合 XPath 和搜索查询
- python - 将函数应用于 numpy 数组的每个矩阵
- java - Idempiere 电子邮件系统
- amazon-web-services - 如何使 ElastiCache 上的 Redis 事件触发 Lambda 函数?
- c++ - 向量容量显示为 0,即使它是保留的
- python-3.x - 为什么我无法获取 tkinter 变量的值?
- vba - 如何在 Access 中创建 VBA 函数以替换表中的任何特殊字符