无法关闭所有切换的div

时间:2014-05-20 07:41:31

标签: javascript jquery html

我想创建两个div(左和右)。如果在左边单击一个链接,它应该在右边div中打开数据,在右边div中有多个问题。每个问题都是可点击的,它会在点击时显示答案。 我已经实现了这个,但是当一个问题打开时,前一个问题不会关闭,我希望它关闭。我使用了切换关闭相同的链接。 我的代码如下

$('.targetDiv').hide();
    $('.show').click(function () {
        $('.targetDiv').hide();
        $('#div' + $(this).attr('target')).toggle();
    });
$('.innerdiv').hide();
$('.answer').click(function(){
   $('.innerdiv').hide(); 
 $('#innerdiv' + $(this).attr('target')).toggle();   
});
<html>
    <div style="width: 30%; float:left">
    <div class="buttons">
     <ul>
      <li><a  class="show" target="1">Placing an Order</a></li>
      <li><a  class="show" target="2">blah.com Returns & Cancellations FAQs</a></li>
      <li><a  class="show" target="3">Brands & Stock</a></li>
      <li><a  class="show" target="4">Shipping & Delivery</a></li>
      <li><a  class="show" target="5">Payment</a></li>
      <li><a  class="show" target="6">Pricing</a></li>
      <li><a  class="show" target="7">Value Added Tax (VAT)</a></li>
      <li><a  class="show" target="8">Privacy & Security</a></li>
      <li><a  class="show" target="9">About the Company</a></li>
      </ul>
    </div>
</div>

<div style="width: 70%; float:right">
   <div id="div1" class="targetDiv">
    <ul>
    <li><a class="answer" target="1">I need personal assistance with my order. Who can I contact?</a><div id="innerdiv1" class="innerdiv" >Our customer service centre is happy to assist you with your order on +91 124 6733300 (10 AM - 7 PM)</div>
    </li>
    <li><a class="answer" target="2" >How do I start a new account?</a><div id="innerdiv2" class="innerdiv">blah blah </div></li>
    <li><a class="answer" target="3">I am having problems ordering through your website. What can I do?</a> <div id="innerdiv3" class="innerdiv"> hahahahah </div></li>
    <li><a class="answer" target="4" >I need personal assistance with my order. Who can I contact?</a> <div id="innerdiv4" class="innerdiv"> b;la ablahhap </div></li>
    <li><a class="answer" target="5" >How do I start a new account?</a><div id="innerdiv5" class="innerdiv">blah blah </div></li>
    </ul>
</div>

1 个答案:

答案 0 :(得分:0)

试试这个: 您必须首先遍历li下的所有ul项,然后关闭&#39;它们

$('.answer').click(function(){
    $(this).closest('ul').find('li').find('.innerdiv').hide(); 
     $('#innerdiv' + $(this).attr('target')).toggle();   
});