除了在.each()中使用.toggle()方法外,子元素一旦显示就无法隐藏

时间:2015-10-08 08:12:27

标签: jquery

这个问题基本上是在我试图回答另一个问题的时候出现的。

问题很简单 - 我的标记如下:

<div class="parent">
    Parent
    <br/>
    <input type="text" value="Element 1"/>
    <div>Element 2</div>
    <span>Element 3</span>
    <input type="button" class="hideParent" value="Hide Children"/>
</div>

以及CSShide .parent div

的所有子元素
.parent>input,.parent>div,.parent>span {
    display: none;
}

现在我要做的是click div.parent {我要展示children div.parent JS$('.parent').on('click',function(){ $(this).children().show(); }); 以下div.parent这一点。

hide

正如您所见,div.parent内部有一个按钮,基本上是hide child的孩子。

我尝试以.toggle() hiding .hide()以各种方式尝试$('.hideParent').on('click',function(){ console.log($(this).closest('.parent').children()) //Logs all the children $(this).closest('.parent').children().hide(); }); ,除了.each()之外,没有人工作过!为什么这种行为发生在以下3种方法中?有人对此有所了解吗?

我为.css元素尝试了不同的方法:

使用display:none

$('.hideParent').on('click',function(){
   console.log($(this).closest('.parent').children())
   $(this).closest('.parent').children().each(function(){
       console.log('here');//Comes here 5 times as there are 5 elements
       $(this).css('display','none !important'); 
   })
});

DEMO

使用.each().hide()更改$('.hideParent').on('click',function(){ console.log($(this).closest('.parent').children()) $(this).closest('.parent').children().each(function(){ console.log('here');//Again I can see this $(this).hide(); }) });

.toggle()

DEMO

使用$.each()$('.parent').on('click',function(){ $(this).children().toggle(); }); $('.hideParent').on('click',function(){ $(this).closest('.parent').children().each(function(){ console.log('here'); $(this).children().toggle(); }) //$(this).closest('.parent').children().toggle(); //Doesn't work });

 Map<String,?> allPrefs = prefs.getAll();      
    for(Map.Entry<String,?> entry : allPrefs.entrySet()){
      String key = entry.getKey();
      String value = entry.getValue().toString();
     }

DEMO

但使用 public String[] fetchAllPreference(){ String[] values = new String(); int index = 0; Map<String,?> allPrefs = prefs.getAll(); for(Map.Entry<String,?> entry : allPrefs.entrySet()){ value[index++] = entry.getValue().toString(); } return values; } 时效果很好但仅在与misfireThreshold

一起使用时才能正常工作
<add key="quartz.jobStore.misfireThreshold" value="60000" />

Working DEMO with $.each()

1 个答案:

答案 0 :(得分:2)

由于事件传播,单击该按钮还会触发附加到parent的点击事件,这将再次设置要显示的子项。

停止点击事件从button传播将解决问题,如

$('.parent').on('click', function () {
    $(this).children().show();
});

$('.hideParent').on('click', function (e) {
    $(this).closest('.parent').children().hide();
    e.stopPropagation();
});

演示:Fiddle

toggle的最后一个解决方案并没有真正起作用,hideParent点击处理程序没有做任何事情,因为parent元素没有大孩子。实际的隐藏/显示是通过toggle点击处理程序

中的parent调用完成的