2015-02-13 5 views
1

У меня есть код, как этотJQuery добавить класс при нажатии и удалить при нажатии на другую

<div class="personal-menu-content"> 
    <ul> 
     <li><a data-menu-item="lessons" class="personal-menu-item lessons" href="#">Lessons</a></li> 
     <li><a data-menu-item="profile" class="personal-menu-item profile" href="#">Edit Profile</a></li> 
     <li><a data-menu-item="library" class="personal-menu-item library" href="#">Your Library</a></li> 
    </ul> 
</div> 

<div class="contents"> 
    <div id="lessons"> 
     <h2>Lessons text here</h2> 
     <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p> 
    </div> 
    <div id="profile"> 
     <h2>profile text here</h2> 
     <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English.</p> 
    </div> 
    <div id="library"> 
     <h2>library text here</h2> 
     <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words,</p> 
    </div> 
</div> 

и JS, как этот

$('div#profile').show(); 
    $('body').on('click','a.personal-menu-item', function(e) { 
     e.preventDefault(); 
     var selectedItem = $(this).attr('data-menu-item'); 
     if(selectedItem == 'lessons') { 
      $('div#lessons').show(); 
      $('div#profile').hide(); 
      $('div#library').hide(); 
     } 
     if(selectedItem == 'profile') { 
      $('div#lessons').hide(); 
      $('div#profile').show(); 
      $('div#library').hide(); 
     } 
     if(selectedItem == 'library') { 
      $('div#lessons').hide(); 
      $('div#profile').hide(); 
      $('div#library').show(); 
     } 
    }); 

так вот я хочу, чтобы, когда я нажимаю на уроках то будет отображаться только содержание уроков, например, когда я нажимаю на профиль и библиотеку, тогда будут показаны только профили и библиотеки. Здесь он работает отлично, но я хотел бы знать, как добавить класс активным, когда один элемент щелкнут внутри этого тега привязки. Предположим, что я нажимаю на уроки, тогда один активный класс должен быть добавлен в тег привязки уроков, и когда я нажимаю на профиль, тогда активный класс следует удалить из тега привязки к уроку, и он должен добавить класс, активный в теге привязки профиля. Вот мой fiddle до сих пор

+0

К сожалению сказать, что, но это, вероятно, самый ужасный, самый тяжелый способ показать/скрыть элементы в списке. Это очень удивительно для кого-то, у кого уровень репутации (почти 3000). Представьте, что у вас есть 20 элементов в вашем списке, вы будете вручную проверять каждый из них при каждом нажатии и вручную скрывать 19 других, обертывая каждый из них в объекте jQuery в каждой строке без кэширования? Мои глаза болят :) Сладкое решение от Void ниже. –

ответ

2

Вы можете просто использовать this ссылки в обработчик щелчка

$('body').on('click.menu', 'a.personal-menu-item', function(e) { 
 
    e.preventDefault(); 
 
    var selectedItem = $(this).attr('data-menu-item'); 
 
    var $selected = $('#' + selectedItem).show(); 
 
    $('.contents > div').not($selected).hide(); 
 
    $('.personal-menu-content .active').removeClass('active') 
 
    $(this).addClass('active'); 
 
}); 
 
$('.personal-menu-content a[data-menu-item="profile"]').trigger('click.menu')
.contents > div { 
 
    display: none; 
 
} 
 
.active { 
 
    color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="personal-menu-content"> 
 
    <ul> 
 
    <li><a data-menu-item="lessons" class="personal-menu-item lessons" href="#">Lessons</a></li> 
 
    <li><a data-menu-item="profile" class="personal-menu-item profile" href="#">Edit Profile</a></li> 
 
    <li><a data-menu-item="library" class="personal-menu-item library" href="#">Your Library</a></li> 
 
    </ul> 
 
</div> 
 

 
<div class="contents"> 
 
    <div id="lessons"> 
 
     <h2>Lessons text here</h2> 
 
     <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p> 
 
    </div> 
 
    <div id="profile"> 
 
     <h2>profile text here</h2> 
 
     <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English.</p> 
 
    </div> 
 
    <div id="library"> 
 
     <h2>library text here</h2> 
 
     <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words,</p> 
 
    </div> 
 
</div>

10

Короткий и сладкий путь.

$(".personal-menu-item").click(function(){ 

$(".personal-menu-item").removeClass("active"); 
$(this).addClass("active"); 

}); 
0

В принципе, спрячьте их все, а затем покажите только тот, который вы хотите. Нужно только изменить две строки :)

Редактировать: Аналогичным образом удалите все активные классы и добавьте их только в тот, который был нажат.

$('body').on('click','a.personal-menu-item', function(e) { 
    e.preventDefault(); 

    $('.personal-menu-content .active').removeClass('active') 

    var selectedItem = $(this).addClass('active').attr('data-menu-item'); 

    $('.contents > div').hide(); 
    $('#' + selectedItem).show(); 
}); 
0

Попробуйте

$('div#profile').show(); 
$('body').on('click','a.personal-menu-item', function(e) { 
    e.preventDefault(); 
    var selectedItem = $(this).parent('li').index(); 
    alert(selectedItem); 
    $('.contents div').hide();   
    $('.contents div').eq(selectedItem).show(); 
}); 

https://jsfiddle.net/pjdq1h83/

Смежные вопросы