2012-09-14 75 views
1

我需要附加到元素的事件处理程序,默认情况下它是不可见的。元素没有附加类时的事件处理程序

在那里,你可以找到几个jQuery选项卡,我定位的选项默认也是不可见的。

<div id="help" class="hidden"> 
    <div id="my-help-tab" class="hidden"> 
     <div class="targeted"> 
      <a href="#" class="show-hide">Show</a> 
      <pre>test</pre> 
     </div> 
    </div> 
</div> 

现在我将如何附加一个事件处理(.toggle()用于显示/隐藏),当元素不会触发hidden类(和它的孩子)?

我当前的解决方案不会在第一次触发,而只会在第二次或第三次点击时触发。

jQuery(document).ready(function($) 
{ 
    $('.targeted').on('click', function(e) 
    { 
     event.preventDefault(); 
     $(this).children('.show-hide').on('click', function(e) 
     { 
      $(this).toggle(
       function(e) 
       { 
        $(this).html('Hide'); 
        $(this).next('pre').toggle(); 
       }, 
       function() 
       { 
        $(this).html('Show'); 
        $(this).next('pre').toggle(); 
       } 
      ); 
     }); 
    }); 
}); 

回答

2

您可以:

jQuery(document).ready(function($) 
{ 
    $('#my-help-tab:not(.hidden) > .targeted > a').on('click', function(e) 
    { 
     event.preventDefault(); 
     $(this).children('.show-hide').on('click', function(e) 
     { 
      $(this).toggle(
       function(e) 
       { 
        $(this).html('Hide'); 
        $(this).next('pre').toggle(); 
       }, 
       function() 
       { 
        $(this).html('Show'); 
        $(this).next('pre').toggle(); 
       } 
      ); 
     }); 
    }); 
}); 

或者:

$('#help:not(.hidden) .targeted > a') 

或(但也许是不必要的):

$('#help:not(.hidden) > #my-help-tab:not(.hidden) > .targeted > a') 

无类的另一种方法

$('#my-help-tab:visible > .targeted > a') 

你应该阅读这些单证:

而对于铁道部阅读this answer关于后代对儿童选择者的解释。

相关问题