我需要一些帮助来及时切换一个问题。我想显示一个问题,当我点击另一个问题时,旧问题就会消失。
这是我的代码
我不知道如何让他们一次出现一个我尝试了很多不同的方法但仍然没有想出任何东西。
<html lang="en">
<head>
<meta charset="UTF-8">
<title>FAQs</title>
<link rel="stylesheet" href="main.css">
<script src="faqs.js"></script>
</head>
<body>
<main id="faqs">
<h1>JavaScript FAQs</h1>
<h2><a href="#" >What is JavaScript?</a></h2>
<div>
<p>JavaScript is a is a browser-based programming language
that makes web pages more responsive and saves round trips to the
server.
</p>
</div>
<h2><a href="#">What is jQuery?</a></h2>
<div>
<p>jQuery is a library of the JavaScript functions that you're most
likely
to need as you develop websites.
</p>
</div>
<h2><a href="#">Why is jQuery becoming so popular?</a></h2>
<div>
<p>Three reasons:</p>
<ul>
<li>It's free.</li>
<li>It lets you get more done in less time.</li>
<li>All of its functions are cross-browser compatible.</li>
</ul>
</div>
</main>
</body>
</html>
"use strict";
var $ = function(id) { return document.getElementById(id); };
// the event handler for the click event of each h2 element
var toggle = function() {
var h2 = this;
// clicked h2 tag
var div = h2.nextElementSibling;
// h2 tag's sibling div tag
// toggle plus and minus image in h2 elements by adding or removing a class
if (h2.hasAttribute("class")) {
h2.removeAttribute("class");
} else {
h2.setAttribute("class", "minus");
}
//toggle div visibility by adding or removing a class
if (div.hasAttribute("class")) {
div.removeAttribute("class");
} else {
div.setAttribute("class", "open");
}
};
答案 0 :(得分:1)
请执行以下操作:
questions
和answers
保存到JS文件中的变量
var questions = $("h2 a");
var answers = $("h2 + div");
questions.on("click", function(event) {
event.preventDefault();
var answer = $($(this).attr("href"));
answers.hide();
answer.show();
});
&#13;
h2 + div {
display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main id="faqs">
<h1>JavaScript FAQs</h1>
<h2><a href="#q1" >What is JavaScript?</a></h2>
<div id="q1">
<p>JavaScript is a is a browser-based programming language
that makes web pages more responsive and saves round trips to the
server.
</p>
</div>
<h2><a href="#q2">What is jQuery?</a></h2>
<div id="q2">
<p>jQuery is a library of the JavaScript functions that you're most
likely
to need as you develop websites.
</p>
</div>
<h2><a href="#q3">Why is jQuery becoming so popular?</a></h2>
<div id="q3">
<p>Three reasons:</p>
<ul>
<li>It's free.</li>
<li>It lets you get more done in less time.</li>
<li>All of its functions are cross-browser compatible.</li>
</ul>
</div>
</main>
&#13;