2013-10-23 178 views
0

在下面的示例中,我试图在用户单击链接时显示div,并且在单击链接时也关闭相同的div显示隐藏链接

问题出现在中间的代码中,该代码检查单击链接时是否可见div。现在,点击相同的链接并不会隐藏div,这正是我所希望的。

我有点卡在这个。这很简单,但我无法想象如何正确使用它。

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Generated by Edit Plus</title> 
<link rel="stylesheet" href="http://localhost/site/css/bootstrap.css" 
     media="screen"> 
<script type="text/javascript" 
     src="http://localhost/site/scripts/jQueryCore.js"></script> 
<script type="text/javascript"> 
$(document).ready(function() { 
    $(".addUser").click(function(){ 
     if($('.demoForm').is(':visible')){ 
      $('.demoForm').hide(); 
     } 
      $(this).parent().find(".demoForm").toggle(); 
    }); 
}); 
</script> 

<style type="text/css"> 
.toolOptions{ 
    display:none; 
} 
</style> 
</head> 

<body> 

<div class="container"> 

     <div> 
     <div class="addUser">Add a new user 
      <span class="demoForm" style="display:none;">I'm the form div.</span> 
     </div> 
     </div> 

     <div> 
     <div class="addUser">Add a new user 
      <span class="demoForm" style="display:none;">I'm the form div.</span> 
     </div> 
     </div> 

     <div> 
     <div class="addUser">Add a new user 
      <span class="demoForm" style="display:none;">I'm the form div.</span> 
     </div> 
     </div> 
</div> 

</body> 
</html> 
+0

所有谁回答 例如,'if'有没有删除任何已有的div可见。我首先查找任何现有的可见div,然后关闭它,然后在它的父级附近打开一个新的div。事情就是这样。 – jmenezes

回答

2

除了以前的答案,你仍然可以使用你的逻辑,只是忽略当前项目。在jsFiddle

$(document).ready(function() { 
    $(".addUser").click(function(){ 
     var form = $(this).find(".demoForm"); 
     $('.demoForm').not(form).hide();   
     form.toggle(); 
    }); 
}); 
+0

你说得对。 – jmenezes

+0

Yw,当我创建jsfiddle示例时有很多答案。不要忘记选择一个作为答案。 –

+0

在你的代码中,我怎样才能挑出只有可见的窗体?页面上的表单可能会有很多,并且每个表单上的行为都会花费时间(就像您的代码一样)。所以form = .demoForm只能看到。那可能吗? – jmenezes

0

用途:

$(".addUser").click(function(){ 
    var $demoForm = $(this).find('.demoForm'); 
    $demoForm.toggle(); 
}); 
0

尝试

$(".addUser").click(function(){ 
     if($('.demoForm').is(':visible')){ 
      $('.demoForm').hide(); 
     } 
      $(this).find(".demoForm").toggle(); 
    }); 

或更好

$(".addUser").click(function(){ 
      $(this).find(".demoForm").toggle(); 
    }); 
0

可以ommit一些行。

$(".addUser").click(function(){ 
     $(this).parent().find(".demoForm").toggle(); 
}); 
4
<script type="text/javascript"> 
$(document).ready(function() { 
    $(".addUser").click(function(){  
     var current=$(this).parent().find(".demoForm");// current element 
      $('.demoForm').not(current).hide(); //hide the rest 
      $(this).parent().find(".demoForm").toggle();//toggle the current 
    }); 
}); 
</script> 

这多少是在js代码就足够了。

干杯!