Javascript 想在打开另一个div时关闭一个div吗

Javascript 想在打开另一个div时关闭一个div吗,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我已经能够让我的divs打开并更改图像,但我想发生的是,当我打开一个时,另一个关闭,我不知道如何进行 我有多个像这样的divs。新闻的每个id都有自己的名字: <div class="article" id="news"> <h2>Hot News: Board Votes to Improve Highways</h2> <p>As Sporktown’s native and tourist population has inc

我已经能够让我的
div
s打开并更改图像,但我想发生的是,当我打开一个时,另一个关闭,我不知道如何进行

我有多个像这样的
div
s。新闻的每个
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>
加上

$('.moreText').slideUp();
在这一行之后:

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

这将向上滑动“.moreText”的所有实例,但当前打开的实例除外。

您可以使用class.articles关闭所有其他div,然后使用div的相应id显示

$(".articles").hide();
$("#news").show();

这将隐藏所有具有类articls的div,并显示id为news的div

获取全局变量,在每个
changetext按钮上分配div的对象/id
单击此变量,获取prevoius id的id并隐藏它

声明全局变量:

window.news;//news is global variable
隐藏/显示div的步骤

$("#"+news).hide();
$("#newdiv").show();
试试这个脚本

$(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'); 
        }

    });

});

您不需要使用变量(全局或局部)来记住哪个div是打开的。
$(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'); 
        }

    });

});