开发者

Change class AND hide div on one click?

I've recentley learnt how to change a class on a click, however i'm now trying something a little more tricky and getting stuck.

I need to change the class on a button click, but also hide a div at the 开发者_如何学Gosame time.

Here's what I have so far:

    <script type="text/javascript">
        $('button').click(function(e) {
            if ($(this).hasClass('grid')) {
                $('#primary ul').removeClass('stylelist').addClass('grid');
                $('#single-style-text').hide();
            }
            else if($(this).hasClass('list')) {
                $('#primary ul').removeClass('grid').addClass('stylelist');
                $('#single-style-text').show();
            }
        });
    </script>

The div #single-style-text is what i'm trying to hide whenever the grid class is active, and have it show when the stylelist class is active.

Is there a better way to write this code?

Thanks


i'd try something like this:

$('button').click(function(e) {
    var button = $(this);
    var hasGrid = button.hasClass('grid');

    $('#primary ul')
        .toggleClass('stylelist', hasGrid)
        .toggleClass('stylegrid', !hasGrid);
    button
        .toggleClass('list', hasGrid)
        .toggleClass('grid', !hasGrid);

    $('#single-style-text').toggle(hasGrid);
});

can give a more specific example if i see some more markup... but this is the basics by toggling classes...

example on jsfiddle: http://jsfiddle.net/Xc7pH/2/


That looks pretty good to me. You could do things a little more efficiently by caching your selectors. E.g.,

// assuming these don't change, cache these outside of click handler
// so that we only have to run these queries once, rather than on
// every click
var $primary = $('#primary ul'),
    $single = $('#single-style-text');

$('button').click(function(e) {
    var $this = $(this);

    if ($this.hasClass('grid')) {
        $primary.removeClass('stylelist').addClass('grid');
        $single.hide();
    } else if($this.hasClass('list')) {
        $primary.removeClass('grid').addClass('stylelist');
        $single.show();
    }
});


Make a style that hides, apply it when you need it and take it away when you don't.

<style ...>
  .noSeeum { display:none }
</style>


<script ...
$('button').click(function(e) {
  if($(this).hasClass('grid')) {
    $('#primary ul').removeClass('stylelist').addClass('grid').addClass('noSeeum');
  } else if($(this).hasClass('list')) {
    $('#primary ul').removeClass('grid').addClass('stylelist').removeClass('noSeeum');
  }
});
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜