jquery show隐藏每个div onclick [英] jquery show hide each div onclick

查看:69
本文介绍了jquery show隐藏每个div onclick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过asp.net生成的动态div数。我需要通过单击其标题来显示每个div内容。我试过这个{

I have a dynamic number of divs which generated through asp.net. I need to show each div contents by clicking on its header. I have tried this {

 $(function () {
            var myHead = $(".toggle-container").find(".toggle-header");
            var myBody = $(myHead).parent().find(".toggle-content");
            $(myHead).click(function () {
                if ($(myBody).css('display') === 'none') {
                    $(this).children('i').removeClass('icon-chevron-sign-down').addClass('icon-chevron-sign-up');
                    $(this).parent().find(".toggle-content").slideDown("slow");
                } else if ($(myBody).css('display') === 'block') {
                    $(this).children('i').removeClass('icon-chevron-sign-up').addClass('icon-chevron-sign-down');
                    $(this).parent().find(".toggle-content").slideUp("slow");

                };
            });
        });

但它仅适用于第一个标题,其余标题不会折叠它的子内容。这是迄今为止我尝试过的 JsFiddle 链接。任何人都可以修复吗?

But it's working only for first header and rest of the headers doesn't collapse it's children content. Here is the JsFiddle Link what I have tried so far. Can anyone give a fix?

推荐答案

问题在于你是如何找到要显示/隐藏的内容的。你需要找到与点击的标题相关的内容你的代码 var myBody = $(myHead).parent()。find(。toggle-content); 应该进入点击处理程序,因为 var myBody = $(this).next()

The problem was how you were finding the content to be displayed/hidden. You need to find the content related to the clicked header you the code var myBody = $(myHead).parent().find(".toggle-content"); should go inside the click handler as var myBody = $(this).next()

 $(function () {
     var myHead = $(".toggle-container .toggle-header");
     $(myHead).click(function () {
         var myBody = $(this).next()
         if ($(myBody).css('display') === 'none') {
             $(this).children('i').removeClass('icon-chevron-sign-down').addClass('icon-chevron-sign-up');
             $(this).parent().find(".toggle-content").slideDown("slow");
         } else if ($(myBody).css('display') === 'block') {
             $(this).children('i').removeClass('icon-chevron-sign-up').addClass('icon-chevron-sign-down');
             $(this).parent().find(".toggle-content").slideUp("slow");

         };
     });
 });

演示:小提琴

注意:上下箭头仍然无效,因为你需要使用 find()而不是 children()

Note: Still the up-down arrows are nor working because you need to use find() instead of children()

但它可以简化为

jQuery(function ($) {
    var $heads = $(".toggle-container .toggle-header");
    $heads.click(function () {
        var $this = $(this);
        $this.find('i').toggleClass('icon-chevron-sign-down icon-chevron-sign-up');
        $this.next().slideToggle("slow");
    });
});

演示:小提琴

这篇关于jquery show隐藏每个div onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆