简体   繁体   English

JavaScript关闭已打开div

[英]JavaScript close already open div

I have given each of my div containers a unique id and some javascript. 我给了我的每个div容器一个唯一的ID和一些JavaScript。 So I can click to Show/Hide each recipe on the page i'm looking at, but I would like to close any already open div via JavaScript when a new one is opened. 因此,我可以单击以显示/隐藏我正在查看的页面上的每个配方,但是当新的div打开时,我想通过JavaScript关闭任何已经打开的div。 I've included some extracted code rather than pasting the entire document as it's huge, below is also the live url: 我包含一些提取的代码,而不是粘贴整个文档,因为它很大,下面也是实时网址:

*update - the <?=$counter_recipes;?> is just producing a unique number. * update- <?=$counter_recipes;?>仅产生一个唯一的数字。 the $i++ method and all further up the page. $ i ++方法,然后在页面的上方。

Live url - http://bit.ly/1hQuzRI 实时网址-http: //bit.ly/1hQuzRI

    <h3 class="box2-title"><?php echo $row_rsCatalogue['pageTitle']; ?></h3>
<a style="color:#000" class="show_hide<?=$counter_recipes;?>">Show/hide</a>

<script type="text/javascript">
$(document).ready(function(){
$("#box_to_show<?=$counter_recipes;?>").hide();
$(".show_hide<?=$counter_recipes;?>").show();

$('.show_hide<?=$counter_recipes;?>').on('click',function(){
$("#box_to_show<?=$counter_recipes;?>").slideToggle();
});

});
</script>
<div class="box2-content" id="box_to_show<?=$counter_recipes;?>">
    <p><?php echo $row_rsCatalogue['pageSubTitle']; ?></p>
    <?php
        if ($row_rsCatalogue['pageId']){
            $rsPriceMatrix = $db->select('pageOption',array('pageId'=>$db->mes($row_rsCatalogue['pageId'])),array('sort'=>'ASC','name'=>'ASC'));
            $ingredients = '';
            while ($row_rsPriceMatrix = $rsPriceMatrix->get_row_assoc()){ 
                $ingredients .= $row_rsPriceMatrix['name'].', ';
            }
            $ingredients = rtrim($ingredients,', ');
            echo '<p>'.$ingredients.'</p>';
        }

    ?>

I can paste more if needed. 如果需要,我可以粘贴更多。

Based on your code: 根据您的代码:

$('.show_hide<?=$counter_recipes;?>').on('click',function(){
    //Hide open divs!
    $("[id^=box_to_show]:visible").slideUp();

    //slide down
    $("#box_to_show<?=$counter_recipes;?>").slideToggle();
});

A much much easier way is to give a common class to your divs that open and close, then just call $(".someClass:visible").slideUp(); 一种简单得多的方法是为打开和关闭的div提供一个通用类,然后只需调用$(".someClass:visible").slideUp(); at the beginning of the function. 在函数的开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM