简体   繁体   English

在javascript中从字符串创建bootstrap-modal

[英]Create bootstrap-modal from string in javascript

I have the following code (which is the HTML from the example): 我有以下代码(这是示例中的HTML):

var modal=
        '<div class="modal fade" id="infoModal"'+id+'tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">'
        +'<div class="modal-dialog">'
        +'<div class="modal-content">'
        +'<div class="modal-header">'
        +'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>'
        +'<h4 class="modal-title">Modal title</h4>'
        +'</div>'
        +'<div class="modal-body">'
        +'<p>One fine body&hellip;</p>'
        +'</div>'
        +'<div class="modal-footer">'
        +'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'
        +'<button type="button" class="btn btn-primary">Save changes</button>'
        +'</div>'
        +'</div>'
        +'</div>'
        +'</div>';
        document.body.appendChild(modal);

And I get the error: 我收到错误:

Uncaught NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null. Uncaught NotFoundError:无法在'Node'上执行'appendChild':新的子元素为null。

If I put the same HTML inside my index.html it works just fine. 如果我在index.html中放入相同的HTML,它就可以了。 What's the problem here? 这有什么问题?

modal is not an element. 莫代尔不是一个元素。 It is just a string. 它只是一个字符串。 appendChild expects an actual element reference, not just a string. appendChild需要一个实际的元素引用,而不仅仅是一个字符串。

While I don't suggest it , you could do 虽然我不建议,但你可以做到

document.body.innerHTML = document.body.innerHTML+modal;

This is lame and will remove your event listeners from anything in the body. 这是蹩脚的,将从正文中的任何内容中删除您的事件侦听器。

You could also do something like: 你也可以这样做:

var div = document.createElement('div');
div.innerHTML = modal;
document.body.appendChild(div);

Live demo (click). 现场演示(点击)。

If I had that amount of markup in string form, I would just put it in an html file and either include it from the server or load it with javascript via ajax. 如果我以字符串形式获得了那么多的标记,我只需将它放在一个html文件中,或者从服务器中包含它,或者通过ajax使用javascript加载它。

You could also create the whole structure using document.createElement for each piece. 您还可以使用document.createElement为每个部分创建整个结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM