jQuery-单击时切换div类 [英] jQuery - Toggle div class on click

查看:56
本文介绍了jQuery-单击时切换div类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不,这不是一个直接的切换问题.我知道toggle()函数以及如何简单地隐藏/显示div.想象一下一个带有标签的盒子:

No, this is not a straight forward toggle question. I am aware of the toggle() functions and how to simply hide/show a div. Imagine a box with a label inside:

<div class="section hidden">
    <div class="section-legend">My Section</div>
</div>

当您单击整个div上的任意位置时,它应删除类hidden.然后,该框看起来已展开.现在,该框不是hidden类,因此不应单击它.

When you click anywhere on the entire div, it should remove class hidden. The box then looks expanded. Now that the box is not of class hidden it should not be clickable.

相反,当您单击div.section-legend时,应再次将类hidden添加到主div中.显然,图例的click事件需要stopPropagation().现在,图例将不再可单击,您必须再次单击整个div才能将其打开.

Instead, when you click the div.section-legend it should add class hidden to the main div again. Obviously the click event for the legend needs to stopPropagation(). Now the legend should not be clickable anymore and once again you must click the entire div to open it.

我什么都无法正常工作,而且我知道这是愚蠢的代码:

I can't get anything to work properly, and I know this is stupid code:

$(document).ready(function() {

    $('.section.hidden').click(function() {
        $(this).removeClass('hidden');
        $(this).find('.section-legend').click(function(e) {
            $(this).parent().addClass('hidden');
            e.stopPropagation();
        });
    });

    $('.section-legend').click(function(e) {
        $(this).parent().addClass('hidden');
        e.stopPropagation();
        $(this).parent().click(function() {
            $(this).removeClass('hidden');
        });
    });

});

推荐答案

$('.section-legend').live('click',function(){
    $(this).parent().toggleClass('hidden');
});

这是假定section-legend与处于隐藏状态"的容器一样大.

This is assuming the section-legend is just as large as it's container in 'hidden state'.

更改了一些代码,解决方法是:

changed some code, solution is this:

$('.section').live('click',function(){
    $(this).removeClass('hidden');
});
$('.section-legend').live('click',function(){
    $(this).parent().toggleClass('hidden'); return false;
});

return false做到了! 演示: http://jsfiddle.net/RUfN7/2/

这篇关于jQuery-单击时切换div类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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