尝试使用jQuery独立显示/隐藏多个列表

Trying to use jQuery to show/hide multiple lists independently

本文关键字:隐藏 列表 显示 独立 jQuery      更新时间:2023-09-26

我有一个网页,我试图在默认情况下隐藏额外的信息。这些额外的部分采用项目列表的形式,我希望用户能够通过单击JavaScript链接来显示或隐藏这些列表。

最初,我使用以下代码:http://jsfiddle.net/4Yk39/2/

 jQuery(document).ready(function() {
   jQuery('.bhlink').click(function(){
     jQuery('ul.billhistory').slideToggle();
   });
 });

…它工作得很好,除了点击页面上的任何JavaScript链接导致所有列表出现或消失,这不是我想要的。我只希望在点击JavaScript链接时,它下面的列表滑出。换句话说,我需要列表独立地出现或消失。

我现在正在使用的代码(来自另一个StackOverflow问题的答案)在这里:http://jsfiddle.net/smZct/

$(document).ready(function () {
$(".billhistory").slideUp();
$(".bhlink").click(function() {
    var billhistory = $(this).closest("p").find(".billhistory");
        var txt = billhistory.is(':visible') ? 'Click to view' : 'Click to hide';
        $(this).text(txt);
        billhistory.stop(true, true).slideToggle("slow");
    });
});

据我所知,一切都设置正确,但是当我点击链接以显示列表时,链接变为"隐藏",但列表实际上并没有出现。

我做错了什么?

jQuery(document).ready(function($) {
    $('.bhlink').on('click', function () {
        $(this).text(function (i, txt) {
            return txt.indexOf('view') != -1 ? 'Click to hide' : 'Click to view';
        }).closest('p').next('.billhistory').slideToggle();
    });
});

小提琴

您需要使用next而不是find作为文本块:

var billhistory = $(this).closest("p").next(".billhistory");