开发者

using JavaScript to insert a lot of html content into a document

开发者 https://www.devze.com 2022-12-12 21:30 出处:网络
I have many many lines of HTML content that I开发者_如何学C need to insert into a document using JavaScript. What the best way to do this? I don\'t want to have it broken out line by line in the sourc

I have many many lines of HTML content that I开发者_如何学C need to insert into a document using JavaScript. 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. 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).

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.


Best way is not to do that.

Put those in static html files, and link it.


Use can use jquery. Eg:

If you have a div with ID = "Sidebar". To load html content with jquery:

$("#Sidebar").HTML("whatever html content");

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.

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.

This Page (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):

<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>
0

精彩评论

暂无评论...
验证码 换一张
取 消