当打开一个div时希望关闭另一个div

5

我已经能够让我的

打开并更改图片,但是我想要的是,当我打开一个时,另一个关闭,我不确定如何去做。

我有多个这样的

。每个新闻的id都是自己的独立名称:

<div class="article" id="news">
    <h2>Hot News: Board Votes to Improve Highways</h2>
    <p>As Sporktown’s native and tourist population has increased, so has traffic. The good news is we are taking steps to deal with it. Before traffic becomes too much of a problem we have a plan to expand current highways and improve current ones.</p>
    <div class="moreText">
        <p>
            As part of the new plan, Route 7 will be expanded from a two-way highway to a four-lane highway. This will dramatically speed up North–South travel through that corridor.
        </p>
        <p>
            In addition to the road widening on Route 7, we have finally received approval to for the extension. The original plan called for Route to continue farther North. The project is finally cleared and work has already begun.
        </p>
    </div>
    <img src="img/more-button.png" width="51" height="16" class="changeTextButton">    
</div>

这是我目前拥有的jQuery脚本:

$(document).ready(function() 
{
    $('.changeTextButton').click( function() 
    {
        $(this).siblings('.moreText').slideToggle(500);
        if ( $(this).attr('src') == 'img/more-button.png') 
        {
            $(this).attr('src', 'img/less-button.png');
        }
        else 
        {
            $(this).attr('src', 'img/more-button.png'); 
        }
    });
});
4个回答

4
您可以使用 .articles 类来关闭所有其他的 div,然后使用相应 div 的 id 来显示,例如:
$(".articles").hide();
$("#news").show();

这将隐藏所有类名为"articls"的div,并显示ID为"news"的div。

2
只需添加 </p>
$('.moreText').slideUp();

在这行之后

$('.changeTextButton').click( function() {

这将会收起除正在打开的之外所有'.moreText'实例。

1
尝试这个脚本。
$(document).ready(function() {
var $parentid = "";

    $('.changeTextButton').click( function() {

          if($parentid!="" && $parentid!=$(this).parent().attr("id")){
               $("#"+$parentid).find(".moreText").slideUp();
          }

        $(this).siblings('.moreText').slideToggle(500);
        $parentid=$(this).parent().attr("id");

        if ( $(this).attr('src') == 'img/more-button.png') {
            $(this).attr('src', 'img/less-button.png');
        }
        else {
            $(this).attr('src', 'img/more-button.png'); 
        }

    });

});

0

取一个全局变量,在每次changeTextButton点击时将div的对象/ID赋值给该变量,然后获取前一个ID并将其隐藏。

声明全局变量:

window.news;//news is global variable

隐藏/显示div
$("#"+news).hide();
$("#newdiv").show();

你不需要使用变量(全局或局部)来记住哪个div是打开的。 - Lee Taylor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接