JQuery: replace DIV contents with html from an external file. Full example?

后端 未结 2 633
醉梦人生
醉梦人生 2020-12-05 20:44

Question

What\'s the full code to enable jQuery on a page and then use it to replace the contents of a DIV with HTML text from an external file?

相关标签:
2条回答
  • 2020-12-05 21:18

    ok, I'll bite...

    <html>
        <head>
            <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
            <script type="text/javascript">
               $(document).ready(function(){
                   $('#selectedTarget').load('includes/contentSnippet.html');
               });
            </script>   
        </head>
        <body>
            <div id="selectedTarget">
                Existing content.
            </div>
        </body>
    </html>
    

    Notes:

    1. I've linked the jquery libraries directly from jQuery's public CDN (which is allowed and encouraged)
    2. You can find the documentation for jQuery's load() function right here.
    0 讨论(0)
  • 2020-12-05 21:25

    To use jQuery on your page, it's generally recommended to place the script before the closing body tag to keep the rest of the page's content from being blocked to load. It's also recommended to use the code from the Google CDN for various benefits Here are some helpful links: http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/ and http://encosia.com/2010/09/15/6953-reasons-why-i-still-let-google-host-jquery-for-me/.

    jQuery Tutorials: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script>
        // your script will go here
    </script>
    </body>
    

    To replace the content of the div with content from another file, this is done with an AJAX request:

    $('#selectedTarget').load('includes/contentSnippet.html');
    

    Obviously there is a lot to learn and much more ways to control and optimize your pages. I would definitely recommend reading the jQuery API documentation to learn more: http://api.jquery.com

    0 讨论(0)
提交回复
热议问题