addClass不起作用(jQuery)

时间:2014-07-13 14:37:38

标签: javascript jquery

我是jQuery的新手,我需要一些帮助。我对addClass有一点问题

这是HTML:

<div class="first">
    Container 1
    <div class="second hide">
        Some text 1
        <div class="close">close</div>
    </div>
</div>
<div class="first">
    Container 2
    <div class="second hide">
        Some text 2
        <div class="close">close 2</div>
    </div>
</div>

和jQuery

$("div.first").click(function() {
    $("div.first").find("div.second").addClass('hide');
    $(this).find("div.second").removeClass('hide');
});

$("div.close").click(function() {   
    $("div.close").parent().addClass('hide');
    $(this).parent().addClass('hide');
});

我需要什么。

  1. 点击容器1.1 - &gt; show container 1.2
  2. 点击容器2.1 - &gt; show container 2.2,hide container 1.2
  3. 点击容器1.1 - &gt; show container 1.2,hide container 2.2
  4. 我上面列出的所有内容都有效。

    现在我需要隐藏所有容器x.2当&#34;关闭&#34;点击。我认为存在冲突,但我不知道在哪里。

    这里是http://jsfiddle.net/E69AN/2/

2 个答案:

答案 0 :(得分:3)

您需要停止点击事件在close按钮上的传播,否则您点击关闭,然后立即重新打开div。试试这个:

$("div.first").click(function() {
    $("div.second").addClass('hide');
    $(this).find("div.second").removeClass('hide');
});

$("div.close").click(function(e) {   
    e.stopPropagation();
    $(this).closest('.second').addClass('hide');
});

Updated fiddle

答案 1 :(得分:2)

当您点击.close div时,这将导致调用2次点击功能,因为它位于div.first内。

  1. 首先执行$("div.close").click(fu....,这将导致隐藏div.first
  2. 立即执行$("div.first").click(fu....,这将导致显示div.first
  3. 您可以通过e.stopPropagation();阻止此行为:

     $("div.first").click(function() {
        $(".second").hide();
        $(this).find(".second").show();
    });
    
    $("div.close").click(function(e) {    
        e.stopPropagation();
        $(this).parent().hide();
    });
    

    jsfiddle

相关问题