简体   繁体   中英

How to load HTML code into a table using Javascript?

I'm building a simple website which consists of a header (the title and a menu) and a table, in which the content is placed (because then I can make the layout easier). The problem is that each time I change the category (click a link in the menu), the whole site becomes white for a short period of time, while it's loading. I'd like it so this doesn't happen, so I only need to load the content of the table, not the whole page. I guess this could easily be done using frames, but I was told that they will stop being supported soon, and that it's a bad practice using them. Is there a way to do this?

For the time being, the site is here, so you can see the effect I'm talking about: http://bljak.org:1235/index.html .

Also, it would be the best if site was just HTML and Javascript, because I'm not really familiar with PHP (and I'm coding on a netbook with 512Mb of RAM, so I doubt I could start a server there).

You can use innerHTML to rewrite the text between the tag and its close tag:

<script type="text/javascript">
function changeText(){
    document.getElementById('tbl').innerHTML = '<table><tr><td>New Text</td></tr></table>';
}
</script>
<div id="tbl"></div> 
<input type="button" onclick="javascript:changeText()" value="Change Text"/>

I will give way based on jQuery - this is the most simple and short way.

First, download the latest jQuery library - can be found here .

Suppose you name your local file "jquery.min.js" have such line in your existing HTML code to "include" the jQuery library:

<script type="text/javascript" src="jquery.min.js"></script>

Now all you need is this code in your page and you're done:

<script type="text/javascript">
    $(document).ready(function() {
        $("a").bind("click", function() {
            var href = $(this).attr("href");

            //bust nasty browser AJAX cache:
            href += "?nnn=" + parseInt(Math.random() * 1000000);

            $("#Container").load(href);
            return false;
        });
    });
</script>

Replace the Container with the ID of the actual element in your page that should contain the "body" then clicking any link will cause the linked page to be loaded into the container without full page reload.

The code is pretty much straightforward, feel free to ask if you want to understand any part of it though.

jQuery is less than 100K so with modern internet speed it really shouldn't be any problem - pure JavaScript is of course possible, but will cause lots of headache in keeping it cross browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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