简体   繁体   English

使用JavaScript将大量html内容插入文档

[英]using JavaScript to insert a lot of html content into a document

I have many many lines of HTML content that I need to insert into a document using JavaScript. 我需要使用JavaScript将许多行HTML内容插入文档中。 What the best way to do this? 最好的方法是什么? I don't want to have it broken out line by line in the source code, and not all stuffed together in a string. 我不想让它在源代码中逐行出现,并且不是全部都塞进一个字符串中。

Have your Javascript code make an AJAX request to the web server for the file that contains the script. 让您的Javascript代码向Web服务器发出AJAX请求,以获取包含脚本的文件。 When the AJAX request comes back, write the contents of the reply to the InnerHTML member on the document (or the document child that should contain the text). 当AJAX请求返回时,将答复的内容写到文档(或应包含文本的文档子级)上的InnerHTML成员。

This page gives a working example of exactly what you want to do - just replace the CGI with a static file containing the content you want to include. 该页面给出了您实际想要做的工作示例-只需用包含要包含的内容的静态文件替换CGI。

Best way is not to do that. 最好的方法是不这样做。

Put those in static html files, and link it. 将它们放在静态html文件中,并将其链接。

Use can use jquery. 使用可以使用jquery。 Eg: 例如:

If you have a div with ID = "Sidebar". 如果您的ID为“ Sidebar”的div。 To load html content with jquery: 要使用jquery加载html内容:

$("#Sidebar").HTML("whatever html content"); $(“#Sidebar”)。HTML(“所有html内容”);

http://docs.jquery.com/Attributes/html http://docs.jquery.com/Attributes/html

You can use jQuery AJAX methods to get the content asynchronously and then use the above method to load it in html. 您可以使用jQuery AJAX方法异步获取内容,然后使用上述方法将其加载到html中。

http://docs.jquery.com/Ajax http://docs.jquery.com/Ajax

You can use an iframe to load the html and use JS to take a part of it in your main page. 您可以使用iframe加载html,并使用JS在您的主页中添加它的一部分。

This Page (main.html)... 此页面(main.html)...

<html>
<head>
    <title>Main</title>
</head>
<body>
    <iframe id="loader" style="display:none"></iframe>
    <div id="target"></div>
    <script>
        function read(b){
            document.getElementById('target').innerHTML = b.innerHTML;
        };
        var ifr = document.getElementById('loader');
        ifr.src = 'testIfrLoad.html#read';
    </script>
</body>
</html>

...loads the content of this one (testIfrLoad.html): ...加载此内容的内容(testIfrLoad.html):

<html>
<head>
    <title>testIfrLoad</title>
    <script>
        function send(){
            top[window.location.hash.substr(1)](document.body);
        }
    </script>
</head>
<body onload="send()">
    <p>Some content</p>
    <p>Some content</p>
    <p>Some content</p>
</body>
</html>

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

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