switching between divs with jquery
suppose i have a list of users....
<a href="#">user1</a>
<a href="#">user2</a>
<a href="#">user3</a>
i want to switch div content related to the user while click on it and also want to align that div to the bottom right corner....i.e.
user1 user2 user3
how i should do that with jquery and $开发者_如何转开发.ajax()
From my understanding, you want to load user-content asynchrnously:
// attach this logic to the clicking of any link with class 'user'
$("a.user").click(function(e){
// prevent default behavior of link
e.preventDefault();
// gather our username from the link
var username = $(this).text();
// fire off a POST, containing our username
$.post("get-content.php", {user:username}, function(response){
// set the HTML of <div id='content'></div> to whatever was received
$("#content").html(response);
// Indicates we're expecting HTML back
}, "html");
});
-- Works with --
<a href="#" class="user">user1</a>
<a href="#" class="user">user2</a>
<a href="#" class="user">user3</a>
<div id="content">
Load a users details
</div>
You don't necessarily need to use Ajax. Just set up the 3 divs on the page and then use jQuery to hide/show.
$(document).ready(function() {
$("div.user_div").hide(); // hides all the user divs at first, so that if someone has JS disabled they'll still see the 3 divs without the hide/show effect
$(".users a").click(function() {
$("div.user_div").hide(); // hide all divs so that only one is showing at a time
var myClass = $(this).attr("class"); // get class of the clicked link
$("div."+myClass).show(); // show the div with the same class as the clicked link
});
});
<div class="users">
<a href="#" class="user1">user1</a>
<a href="#" class="user2">user2</a>
<a href="#" class="user3">user3</a>
</div>
<div class="user_div user1">
...content...
</div>
<div class="user_div user2">
...content...
</div>
<div class="user_div user3">
...content...
</div>
If you don't have a ton of divs to show/hide, Ajax is probably overkill.
精彩评论