【问题标题】:Toggling a single element within a class when other div is clicked Jquery单击其他div时切换类中的单个元素Jquery
【发布时间】:2013-03-29 08:45:15
【问题描述】:

我正在尝试为 wordpress 构建设置一个简单的评论切换。

CSS

<div class="commenttoggle">
    <p class="popcom">Show Comments</p>
                                     ~~~Clickable Button~~~~~~
</div>
<div id="comments" class="comments-area">
                                     ~~~~PHP code calling WP comments~~~
</div>

jQuery

    jQuery(document).ready(function($) {
       $('.comments-area').hide();

           $('.commenttoggle').click(function() {
             $('.comments-area').toggle();
           });
       });

上面的代码有效,但是当我单击一篇文章下的显示 cmets 按钮时,所有 cmets 部分都会显示。我一直在查看 jQuery api & here at stackoverflow,但似乎找不到任何关于仅切换最接近点击事件的元素的建议。

我已经尝试过 .closest 和 .parent 但我似乎无法让它工作。我真的很感激一些代码,但也有一个解释,因为我刚开始使用 jQuery。

【问题讨论】:

    标签: jquery css


    【解决方案1】:

    这应该做你想做的:

    jQuery(document).ready(function($) {
        $('.comments-area').hide();
        $('.commenttoggle p').click(function() {
            $(this).closest("div").next('.comments-area').toggle();
        });
    });
    

    【讨论】:

    • 是的,这正是我想要的,谢谢你的时间和经验
    【解决方案2】:

    您需要使用each 迭代具有相同类popcom 的元素并应用$(this) 来定位单击的元素

    $('.popcom').each(function() {
        $(this).click(function() {
            // Your script here              
        });
    })
    

    注意:.popcom 是显示评论按钮的类

    【讨论】:

    • 感谢您的快速回答,非常感谢我会看看我是否可以让它工作。
    猜你喜欢
    • 2018-03-17
    • 1970-01-01
    • 2019-03-14
    • 2015-09-22
    • 2020-11-23
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多