用jquery在div之间切换

时间:2010-01-03 17:27:54

标签: php ajax

假设我有一个用户列表....

<a href="#">user1</a>
<a href="#">user2</a>
<a href="#">user3</a>

我想在点击它时切换与用户相关的div内容,并且还想将该div对齐到右下角....即

user1 user2 user3

我应该如何使用jquery和$ .ajax()

2 个答案:

答案 0 :(得分:4)

根据我的理解,您希望异步加载用户内容:

// 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");
});

- 使用 -

<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>

答案 1 :(得分:1)

您不一定需要使用Ajax。只需在页面上设置3个div,然后使用jQuery隐藏/显示。

$(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>

如果你没有显示/隐藏大量的div,Ajax可能有点过分。