用户配置文件侧面菜单并根据点击更改内容

时间:2016-09-28 15:26:08

标签: javascript jquery html

我想要html菜单,用户可以在其中单击,然后页面更改内容。它就像用户个人资料页面,其中用户有列表,如帐户,账单,图片等,

 <li><a href=""  data-box="index"><i class="fa fa-user"></i> My Profile</a></li>
 <li><a href=""  data-box="account"><i class="fa fa-edit"></i> Edit Profile</a></li>
 <div class="box index">
     @include("partials.profile_index") 
    </div>
  <div class="box account">
     @include("partials.profile_account") 
    </div>
<script>

$(document).ready(function(){

$('a').click(function(ev){
    ev.preventDefault();

    // hide everything
   $('.box').not(
       // except the corresponding box
       $('.box.'+$(this).data('box')+':hidden').fadeIn()
   ).fadeOut(); 
});

});


</script>

3 个答案:

答案 0 :(得分:1)

我清理了一些代码,并添加了一些注释以供解释。这应该适合您,也有助于将来的调试。最后,我还确保传出的框动画在传出框完成动画后发生。 See this fiddle

$(document).ready(function(){

  // hide all boxes by default.
  $('.box').hide();

  // when someone clicks a link, process hiding/showing the correct box
  $('a').click(function(ev){

    // stop the default action for the click event.
    ev.preventDefault();

    // assign a friendly variable for the current box
    var currentBox = $(this).attr("data-box");

    // hide everything except for the box we want to show
    $('.box').not('.' + currentBox).fadeOut('slow', function() {

      // after the animation is complete fade in the box we want to show.
      $('.box.' + currentBox).fadeIn('slow');

    }); 

  });

});

答案 1 :(得分:1)

您写道:“...点击然后页面更改内容...”所以我假设您希望浏览器重新加载页面而不是简单地通过JavaScript更新DOM。如果我误解了你的问题,请原谅。

我通常如何处理这个问题的方法是将一个名为“action”的URL变量分配给我的链接。这样,当页面重新加载时,我知道要显示哪些内容。

您的代码可能会因您使用的服务器端语言而异。我将使用CFML进行演示,但无论您是否使用PHP等,逻辑都应该相同。

以下是您的链接外观的示例:

 <ul>
   <li><a href="index.cfm?action=myProfile" data-box="index"><i class="fa fa-user"></i> My Profile</a></li>
   <li><a href="index.cfm?action=editProfile" data-box="account"><i class="fa fa-edit"></i> Edit Profile</a></li>
 </ul>

然后你会在index.cfm页面上提供某种类型的服务器端逻辑,如下所示:

<!--- does the user want to view his/her profile? --->
<cfif action IS "myProfile">

    <div class="box index">
      @include("partials.profile_index") 
    </div>

</cfif>

<!--- does the user want to edit his/her profile? --->
<cfif action IS "editProfile">

    <div class="box index">
      @include("partials.profile_account")
    </div>

</cfif>

使用此解决方案,您不需要任何JavaScript。只需使用URL变量创建普通链接,这些变量描述了您希望目标页面在加载时显示的内容。

答案 2 :(得分:0)

您可以按照以下方式进行操作。查看演示 - Fiddle Demo

$(document).ready(function(){

    $('a').click(function(ev){
        ev.preventDefault();

        // hide everything
        var $thisBox = $('.box.' + $(this).data('box') );
        $('.box').not( $thisBox ).fadeOut();
        if ( $thisBox.is(':hidden') ) {
            $thisBox.fadeIn();
        }
    });

});