最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Removeadd class on click of a button - Stack Overflow

programmeradmin0浏览0评论

I'd like to be able to remove one class from a div and add another upon the click of a button. But I can't get it to work.

<div class="hiddennav displaynone">
  <ul>
    <?php wp_nav_menu(array('menu' => 'Main Nav menu')); ?>
  </ul>
</div> <!-- end div hiddennav -->
<div class="fixednav">
  <div class="shownav"><a href="#" class="shownavbutton"></a></div>
  <!-- end div shownav -->
</div> <!-- end div fixednav -->

Here's the jQuery:

$(document).ready(function(){
  $(".shownavbutton").click(function() {
    $(".hiddennav").removeClass("displaynone").addClass("displayblock");
  });

I'd preferably want it to toggle the classes too when clicked multiple times.

I'd like to be able to remove one class from a div and add another upon the click of a button. But I can't get it to work.

<div class="hiddennav displaynone">
  <ul>
    <?php wp_nav_menu(array('menu' => 'Main Nav menu')); ?>
  </ul>
</div> <!-- end div hiddennav -->
<div class="fixednav">
  <div class="shownav"><a href="#" class="shownavbutton"></a></div>
  <!-- end div shownav -->
</div> <!-- end div fixednav -->

Here's the jQuery:

$(document).ready(function(){
  $(".shownavbutton").click(function() {
    $(".hiddennav").removeClass("displaynone").addClass("displayblock");
  });

I'd preferably want it to toggle the classes too when clicked multiple times.

Share Improve this question edited Oct 12, 2012 at 17:16 dda 6,2132 gold badges27 silver badges35 bronze badges asked Oct 12, 2012 at 17:12 andyandy 2,7548 gold badges49 silver badges63 bronze badges 2
  • 4 you got far enough to add "want it to toggle the classes" , but not far enough to google "jQuery toggle class" because you'd find toggleClass() – Scott Selby Commented Oct 12, 2012 at 17:15
  • 1 Looks like you're missing an extra }); to end the $(document).ready() function. – Marcus Commented Oct 12, 2012 at 17:17
Add a ment  | 

2 Answers 2

Reset to default 5

Try $(selector).toggleClass(class):

$(document).ready(function(){ 
    $(".shownavbutton").click(function() { 
        $(".hiddennav").toggleClass("displaynone").toggleClass("displayblock");
    });
});

Optionally, you could use the CSS method as well (assuming that this is all you're acplishing via your displaynone and displayblock classes):

$(".hiddennav").toggle(function() {
    $(this).css('display','none');
}, function() {
    $(this).css('display','block');
});

Try this

 $(".hiddennav").toggleClass("displaynone displayblock");
发布评论

评论列表(0)

  1. 暂无评论