Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...