add class to ajax trigger

时间:2017-08-05 11:30:04

标签: javascript jquery ajax

I've created a simple ajax loading content which works but I'm trying to change the class 'active' (it adds a border-bottom to let the user know which menu they are looking at) depending on which target has been clicked. I've attempted using jquery but to no avail. If someone could help or point me in the right direction it would be greatly appreciated.

This is my attempt:

     $(document).on('click', '.menu-tabs li a', function () {
      $('.active').removeClass('active');
      $(this).parent().addClass('active');
    });

HTML:

<div class="menu-tabs" id="menu-tabs">
  <ul>
   <li class="active"><a href="#" data-target="food">FOOD</a></li>
   <li class=""><a href="#" data-target="desserts">DESSERTS</a></li>
   <li class=""><a href="#" data-target="drinks">DRINKS</a></li>
  </ul>
 </div>

 <article class="menu-container" id="menu-container">
   <?php include('food.php'); ?>
  </article>

AJAX:

var trigger = $('#menu-tabs ul li a'),
    container = `$('#menu-container');

trigger.on('click', function () {

    var $this = $(this),
        target = $this.data('target');

    container.load(target + '.php');

    return false;
});`

2 个答案:

答案 0 :(得分:0)

Please check the below code section. Taken mostly from your own code. Just added the CSS for checking and it seems to work for me. At-least the navigation is changing "active" class on click.

$(document).on('click', '.menu-tabs li a', function() {
  $('.active').removeClass('active');
  $(this).parent().addClass('active');
});
.active{
  background:green;  
}
.active a{
  color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="menu-tabs" id="menu-tabs">
  <ul>
    <li class="active"><a href="#" data-target="food">FOOD</a></li>
    <li class=""><a href="#" data-target="desserts">DESSERTS</a></li>
    <li class=""><a href="#" data-target="drinks">DRINKS</a></li>
  </ul>
</div>

<article class="menu-container" id="menu-container">
  <?php include('food.php'); ?>
</article>

答案 1 :(得分:-1)

老实说,我只是把这两个代码合并起来就可以了。

let fabMenuController=...