问题描述:

I've just made a really simple toggle button. Function checks the state (a class), and executes resizing animation/re-sets state.

But when clicked, somehow both cases are triggered (target div appears and disappears). How can this happen with just one click?

$('.box').live('click',function(){

if ($(this).hasClass('.op'))

{

$(this).siblings('.lh').animate({ width: '0', marginLeft: '80'}, 300);

$(this).removeClass('.op');

} else

{

$(this).siblings('.lh').animate({ width: '80', marginLeft: '0'}, 300);

$(this).addClass('.op');

}

});

网友答案:

You don't use dot notation when referring to classes for the class manipulation functions.

It should be .addClass('op'), .removeClass('op') and .hasClass('op') - that should fix it for you.

网友答案:

box.hasClass('.op') try without dot. like box.hasClass('op') but I guess this is not the real problem

$('.box').live('click',function(){

          if ($(this).hasClass('op'))
          {
             $(this).siblings('.lh').animate({ width: '0', marginLeft: '80'}, 300);
             $(this).removeClass('op');
          } else {
             $(this).siblings('.lh').animate({ width: '80', marginLeft: '0'}, 300);
             $(this).addClass('op');
          }
    });
网友答案:

I wouldn't use live. Instead, try click:

$('.box').click(function(){
          if ($(this).hasClass('.op'))
          {
             $(this).siblings('.lh').animate({ width: '0', marginLeft: '80'}, 300);
             $(this).removeClass('.op');
          } else
          {
             $(this).siblings('.lh').animate({ width: '80', marginLeft: '0'}, 300);
             $(this).addClass('.op');
          }
    });

http://api.jquery.com/click/

相关阅读:
Top