dongpi2503 2016-12-12 04:22
浏览 35

使用Ajax和PHP动态更新导航栏

I am using the following code snippet from John Morris to investigate how Ajax might work for dynamically updating my menu:

<script>
  $(document).ready(function(){
    var trigger = $('#bs-example-navbar-collapse-1 ul li a'),
    container = $('#navbar_content');

    trigger.on('click', function(){
      var $this = $(this), target = $this.data('target');
      container.load(target + '.php');
      return false;
    });
  });
</script>

I also have this html code:

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  <ul class="nav navbar-nav" id='navbar_content'>
    <li class="active"><a href="#" data-target="object1">object1</a></li>
    <li><a href="#" data-target="object2"></a></li>
    <li><a href="#" data-target="object3"></a></li>
    <li><a href="#" data-target="object4"></a></li>
  </ul>
</div>

which I would like to dynamically replace with this code when object 2 is clicked (to change the class of the selected hyperlink) - there is simlar code in object3.php and object4.php:

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  <ul class="nav navbar-nav" id='navbar_content'>
    <li><a href="#" data-target="object1">object1</a></li>
    <li class="active"><a href="#" data-target="object2"></a></li>
    <li><a href="#" data-target="object3"></a></li>
    <li><a href="#" data-target="object4"></a></li>
  </ul>
</div>

Everything works well on my first click of object 2, but subsequent clicks of other links will not update the navbar. I think this is related to bindings but I can not figure out what needs to be done to fix this. All suggestions appreciated.

  • 写回答

1条回答 默认 最新

  • duannaozhao4626 2016-12-12 04:40
    关注

    Since you are overwriting the links inside #navbar_content, you need to use event delegation - see https://learn.jquery.com/events/event-delegation/

    So instead of binding to

    var trigger = $('#bs-example-navbar-collapse-1 ul li a')
    

    you need to bind to your container and use event propagation. Try with something like -

    <script>
      $(document).ready(function(){
        var container = $('#navbar_content');
    
        container.on('click', 'li a', function(){
          var $this = $(this), target = $this.data('target');
          container.load(target + '.php');
          return false;
        });
      });
    </script>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?