How to just select a portion of the content loaded and inject just that part into the current webpage.
Using a similar example to my previous post, the current webpage that we wish to inject content into has a placeholding <div> that looks like this:
We can load content into this with the following Javascript snippet (as long as we've also included the jQuery library) from the page /path/to/foo.html:
If foo.html is a regular HTML page containing <html> <script> etc tags then it can completely screw with your existing page, so it either just needs to contain very basic content, or you can inject just a section of the page into your current webpage.
For example, if foo.html contains something along these lines:
and we only wanted to load the navigation list into our current webpage into #foo, we can do this:
Note that we have specified #navigation after the path to the filename to be loaded. This tells jQuery to only inject the element #navigation into our current webpage's #foo element. The resulting #foo <div> would now look like this:
You can use any normal jQuery selectors to choose which elements to inject into the current webpage, so the following would be equally valid:
This would just load the <li> elements from #navigation, resulting in invalid HTML but the jQuery call would succeed.
As noted in the previous post, using .load() in this way will not produce any way of tracking errors if the content could not be loaded. Future posts will look at other ways to load content and look for errors. jQuery/Javascript posts are made on Tuesdays and Sundays so make sure to sign up to my RSS feed (see below) to make sure you don't miss out.
0 comments:
Post a Comment