1

I have what you'll probably think is a very simple jQuery question. (I'm very new to this.)

I have a menu made up of a bunch of <h2>s, and I'd like each menu item to move to one side when clicked, returning to its original position when a different menu item is clicked. I'm doing this with 'animate' in jQuery. I thought I could do this by adding an ".active" class and using .not('.active') in my jQuery selector so that if the user clicks on the menu item repeatedly it won't just keep moving across the screen; however, it's not working correctly, and I think that's because changing classes aren't taken into account when I use $(document).ready. So I'm trying to use .on instead, but I'm floundering in the terminology. I wanted to use it with .not, but I read on this site that that can't be done; so I switched things up and tried to create an ".*in*active" class -- but that's not working for me either.

Original $(document).ready code:

$(document).ready(function() {
    $('.menu-item').not('.active').click(function() {
        $(this).siblings('.active').animate({left: '-=120px'}, '1000');
        $(this).siblings('.active').removeClass('active'); 
        $(this).animate({left: '+=120px'}, '1000');
        $(this).addClass('active');
    });
});

Attempt at using .not:

$('.menu-item .inactive').on('click', function(event) {
        $(this).siblings.not('.inactive').animate({left: '-=120px'}, '1000');
        $(this).siblings.not('.inactive').addClass('inactive'); 
        $(this).animate({left: '+=120px'}, '1000');
        $(this).removeClass('inactive');
});

Any ideas on why the .not version isn't working, or (if possible) how I can get this thing to work just using $(document).ready?

4

1 回答 1

0

它不起作用,因为$('.menu-item').not('.active')会在事件注册发生时过滤元素,然后我认为没有任何菜单项具有分配给它的活动类。

你应该有的解决方案是

$(document).on('click', '.menu-item:not(.active)', function(){
    //do
})
于 2013-06-26T06:48:31.137 回答