I have a menu like this, but the mark-up doesn't have to stay this way.
<div id="menu">
<ul>
<li><a href="#item1">Item 1</a></li>
<ul>
<li><a href="#subitem1">Subitem 1</a></li>
</ul>
<li><a href="#item2">Item 2</a></li>
</ul>
</div>
And each time one of these menu items is clicked I want to load different content in a div - let's call it #content.
$(document).ready(function() {
开发者_StackOverflow $('#menu li').click(function(){
$('#content').load('content.txt');
});
});
Now, how do I pass which content page I want to load into #content? Thanks in advance!
Prevent the click from going to the page with the event's preventDefault() method, use the link's href that actually goes to that page loaded into the #content div.
$(document).ready(function() {
$('#menu a').click(function(e){
$('#content').load($(this).attr('href'));
e.preventDefault();
});
});
<div id="menu">
<ul>
<li><a href="page1.html">Item 1</a></li>
<ul>
<li><a href="subpage1.html">Subitem 1</a></li>
</ul>
<li><a href="page2.html">Item 2</a></li>
</ul>
</div>
You can do this in numerous ways. Essentially, you need to associate a URL with each <li>
item.
To name a few ways, you could have them stored in a JavaScript array, in the jQuery cache i.e. $(selector).data
, in a hidden input inside each <li>
element, as an attribute on the <li>
element.
I'd use something like jQuery UI's tab feature to handle this. It will probably degrade better.
If you need to do this manually, your easiest route may be to add an ID or rel attribute to the anchors, and then use that to determine the content page you want to load.
You can use "$(this).attr('blah');" within your function to access these properties.
in the realms of progressive enhancement - you should make the links point to another page with their respective content.
then you can load not just the entire contents of the page into your content div but a specified element. So if its the contents of the #content div in the other page is required something like:
$('#menu a').click(function(){
$('#content').load($(this).attr('href') + ' #content');
});
should do the trick.
only problem with joelpittets solution is that it would load the ENTIRE contents of the other page which may not be what is desired. He did however remember to cancel the default behaviour of clicking a link...
精彩评论