Jquery if 语句帮助
我想知道如何用jquery正确编写if语句。我有一堆 div,每个 div 中都有一个锚点,当单击时,会使用toggleClass 扩展 div 的宽度。这工作正常,但我想编写一个 if 语句来检查其他 div 是否应用了相同的类,如果是,则收缩该 div,然后展开下一个 div (希望有意义),到目前为止我的代码:
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>
<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');
});
});
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>
<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');
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以这样做,在这种情况下不需要 if:
这会切换父级上的宽类,然后从其所有兄弟姐妹中删除该类。
You can do that like this, no need for an if in this case:
This toggles the wide class on the parent, then removes the class from all it's siblings.
不需要 if 语句,只需在应用了
wide
类的任何对象上运行removeClass()
即可:出于性能考虑,只需使用
addClass()
和removeClass()
而不是toggleClass()
No need for an if statement, just run
removeClass()
on anything that has thewide
class applied to it:And for performance sake, just use
addClass()
andremoveClass()
instead oftoggleClass()
你想写这样的东西:
You want to write something like this: