JQuery: replace DIV contents with html from an ext

2020-01-31 03:54发布

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?

Background

I'm brand new to jQuery and I'm eager to work with it so I can learn it. I have a site where I need to replace the contents of the same div (a footer) that exists on every page. Fortunately, each of these pages already imports the same header file. So I'm going to modify that header file with some jQuery magic! I'm having trouble finding full examples and I figured other's might have similar questions. Who better to ask than the SO gurus?

Example

Given a basic HTML file Example.html:

<html>
    <head>
    </head>
    <body>
        <div id="selectedTarget">
            Existing content.
        </div>
    </body>
</html>

And an external file includes/contentSnippet.html containing a snippet of html:

<p>
    Hello World!
</p>

What would the new Example.htmlfile be that would link the proper jQuery libraries (from the ./js directory) and replace the div's contents via jQuery?

2条回答
倾城 Initia
2楼-- · 2020-01-31 04:11

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.
查看更多
Fickle 薄情
3楼-- · 2020-01-31 04:15

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

查看更多
登录 后发表回答