javascript - 在 if 语句中使用 $(this)

标签 javascript jquery

我正在尝试制作一个带有 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/

相关文章:

javascript - JQM 复选框在点击时被选中,然后立即在 android 上变为未选中状态

javascript - JS jQuery 每个循环过滤器追加列表

javascript - 具有总和(未计数)的聚类传单标记总计 : how to get consistent round red shape and label format like in unclustered markers

ajax - 如何在没有 JSF 标记库的情况下编写 <table> 标记 (h :datatable or ui:repeat) but still use JSF for controlling page flow

jquery - 像药丸一样制作精美的单选按钮

php - 如何将值从 jquery 发布到 php

javascript - jQuery mouseoverIntent 插件可以在 Internet Explorer 中使用吗?

javascript - 通过 AJAX 更新 Pickadate 输入

javascript - 如何影响点击google map?

javascript - AngularJs 将查询字符串发布到 C# Controller