我正在尝试制作一个带有 3 个面板的 Accordion ,因此当我单击一个面板时,其内容应该出现,而当我再次单击它时,其内容应该消失
这是jquery代码
jQuery(".item").click(function() {
if ( jQuery(".content").css("display") == "block" )
{
jQuery(this).css("display", "none");
}
else if ( jQuery(".content").css("display") == "none" )
{
jQuery(this).css("display", "block");
}
}
但是这里的问题是,这里的jQuery(this)当然指的是".item"类,点击时整个面板就会消失。
所以我想引用“.content”,以便仅应该显示或不显示正在单击的面板的内容。
这是 HTML 代码:
<div class="container">
<div calss="row">
<div class="accordion">
<div class="item">
<div class="content"></div>
</div>
<div class="item">
<div class="content"></div>
</div>
<div class="item">
<div class="content"></div>
</div>
</div>
</div>
</div>
我试过了
jQuery(".item").click(function() {
if ( jQuery(".content").css("display") == "block" )
{
jQuery(".content").css("display", "none");
}
else if ( jQuery(".content").css("display") == "none" )
{
jQuery(".content").css("display", "block");
}
}
但是当单击时,所有 3 个面板的内容都会出现/消失。如有任何建议,我们将不胜感激
最佳答案
如果您在 jQuery
的第二个参数中传递 this
,它将在 this
中查找 .content
。就像这样:
jQuery(".item").click(function() {
if ( jQuery(".content", this).css("display") == "block" )
{
jQuery(".content", this).css("display", "none");
}
else if ( jQuery(".content", this).css("display") == "none" )
{
jQuery(".content", this).css("display", "block");
}
})
您的点击处理程序正在使用选择器查找所有元素,因此传递 this
将限制查找要隐藏/显示的元素的范围。
要优化此代码,请尝试存储到变量中,因为调用 jQuery
/$()
可能会很昂贵,特别是当您需要在处理程序内多次访问该元素时。您可以使用 toggle
函数将其状态从可见切换到隐藏,反之亦然。
jQuery(".item").click(function() {
jQuery(".content", this).toggle();
});
关于javascript - 在 if 语句中使用 $(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36933738/