开发者

Jquery if statement help

I want to know how to correctly write an if statement with jquery. I have a bunch of div's with an anchor in each that when clicked expands the the div's width using toggleClass. This works fine but I want to write an if statement that checks to see if the other div's have the same class applied, if so contract that div, then expand the next div (hope that makes sense), my code so far:

HTML:

<div class="content-block">
    <h2>Title</h2>
    <p>Content...</p>
    <a class="expand" href="#">Expand View</a>
</div>
<div class="content-block">
    <h2>Title</h2>
    <p>Content...</p>
    <a class="expand" href="#">Expand View</a>
</div>
<div class="content-block">
    <h2>Title</h2>
    <p>Content...</p>
    <a class="expand" href="#">Expand View</a>
</div>开发者_Python百科
<div class="content-block">
    <h2>Title</h2>
    <p>Content...</p>
    <a class="expand" href="#">Expand View</a>
</div>

JQUERY:

$(document).ready(function(){
$('a.expand').click(function(){
    $(this).parent('.content-block').toggleClass('wide');
});

});


You can do that like this, no need for an if in this case:

$(document).ready(function(){
  $('a.expand').click(function(){        
    $(this).parent('.content-block').toggleClass('wide')
           .siblings('.wide').removeClass('wide');
  });
});

This toggles the wide class on the parent, then removes the class from all it's siblings.


No need for an if statement, just run removeClass() on anything that has the wide class applied to it:

$(document).ready(function(){
    $('a.expand').click(function(){
        $('.content-block.wide').removeClass('wide');
        $(this).parent('.content-block').addClass('wide');
    });
});

And for performance sake, just use addClass() and removeClass() instead of toggleClass()


You want to write something like this:

var otherExpanded = $('.content-block.wide');
if (otherExpanded.length)
    //Do things
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜