显示其他div时隐藏div

Tan*_*ane 1 html javascript css jquery

我正在建立一个包含3个按钮的页面,每个按钮都打开一个不同的div元素。我想要的是一次只显示一个格。因此,当一个div打开时,另一个div应该关闭。

我设法创建了每个打开不同的div元素的按钮。但我想不出一种方法,当其他div打开时自动关闭div。

var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var button3 = document.getElementById("button3");
var content1 = document.getElementById("content1");
var content2 = document.getElementById("content2");
var content3 = document.getElementById("content3");
content1.style.display = "none";
content2.style.display = "none";
content3.style.display = "none";
button1.addEventListener("click", showContent1);
button2.addEventListener("click", showContent2);
button3.addEventListener("click", showContent3);

function showContent1() {
  if (content1.style.display !== "none") {
    content1.style.display = "none"
  } else {
    content1.style.display = "block";
  }
}

function showContent2() {
  if (content2.style.display !== "none") {
    content2.style.display = "none"
  } else {
    content2.style.display = "block";
  }
}

function showContent3() {
  if (content3.style.display !== "none") {
    content3.style.display = "none"
  } else {
    content3.style.display = "block";
  }
}
Run Code Online (Sandbox Code Playgroud)
#button1,
#button2,
#button3 {
  width: 50px;
  height: 50px;
  background: lightblue;
  margin: 5px;
  cursor: pointer;
}

#content1,
#content2,
#content3 {
  width: 100px;
  height: 50px;
  background: blue;
  color: white;
  margin: 5px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="button1">button 1</div>
<div id="button2">button 2</div>
<div id="button3">button 3</div>
<div id="content1">content 1</div>
<div id="content2">content 2</div>
<div id="content3">content 3</div>
Run Code Online (Sandbox Code Playgroud)

Car*_*sen 6

您可以将代码缩减为以下形式:

$("[id^=button]").click(function() {
  var id = $(this).attr("id").replace("button", "")
  $("#content" + id).toggle();
});
Run Code Online (Sandbox Code Playgroud)

下面的代码将只允许1格同时显示。

$("[id^=button]").click(function() {
  var id = $(this).attr("id").replace("button", "");
  $("[id^=content]").hide()
  $("#content" + id).show();
});
Run Code Online (Sandbox Code Playgroud)

在这里,我们使用^来表示我们希望所有元素都button以触​​发click事件开头。

演示版

$("[id^=button]").click(function() {
  var id = $(this).attr("id").replace("button", "")
  $("#content" + id).toggle();
});
Run Code Online (Sandbox Code Playgroud)
$("[id^=button]").click(function() {
  var id = $(this).attr("id").replace("button", "");
  $("[id^=content]").hide()
  $("#content" + id).show();
});
Run Code Online (Sandbox Code Playgroud)
$("[id^=button]").click(function() {
  var id = $(this).attr("id").replace("button", "")
  $("#content" + id).toggle();
});
Run Code Online (Sandbox Code Playgroud)

  • @Wimanicesir如果他正在添加jQuery,那么我认为他接受jQuery解决方案。 (2认同)