我正在从“JavaScript和jQuery:缺失手册”一书中做这个例子,在这里我们构建了一个动态FAQ部分。这个想法是,当你点击一个问题时,答案就会出现,如果你再次点击这个问题,答案就会消失。我的问题是,有时我不得不在问题上点击两次,才能使答案出现/消失。这就好像单击事件不是随机触发的。
下面是代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>A One Page Faq</title>
<link href="../_css/site.css" rel="stylesheet">
<script src="../_js/jquery-1.11.1.min.js"></script>
<style type="text/css">
h2 {
background: url(../_images/open.png) no-repeat 0 11px;
padding: 10px 0 0 25px;
cursor: pointer;
}
h2.close {
background-image: url(../_images/close.png);
}
.answer {
margin-left: 25px;
}
</style>
<script>
$(document).ready(function() {
$('.answer').fadeOut(1);
var hidden = true;
$('.main h2').click(function() {
if (hidden) {
$(this).next('.answer').fadeIn();
hidden = false;
}
else {
$(this).next('.answer').fadeOut();
hidden = true;
}
});
}); // end ready
</script>
</head>
<body>
<div class="wrapper">
<div class="header">
<p class="logo">JavaScript <i>&</i> jQuery <i class="mm">The<br>Missing<br>Manual</i></p>
</div>
<div class="content">
<div class="main">
<h1>A One Page FAQ</h1>
<h2>I've heard that JavaScript is the long-lost fountain of youth. Is this true?</h2>
<div class="answer">
<p>Why, yes it is! Studies prove that learning JavaScript freshens the mind and extends life span by several hundred years. (Note: some scientists disagree with these claims.)</p>
</div>
<h2>Can JavaScript really solve all of my problems?</h2>
<div class="answer">
<p>Why, yes it can! It's the most versatile programming language ever created and is trained to provide financial management advice, life-saving CPR, and even to take care of household pets.</p>
</div>
<h2>Is there nothing JavaScript <em>can’t</em> do?</h2>
<div class="answer">
<p>Why, no there isn’t! It’s even able to write its own public relations-oriented Frequently Asked Questions pages. Now that’s one smart programming language!</p>
</div>
</div>
</div>
</body>
</html>发布于 2014-06-09 04:51:31
问题是你对每个答案都使用了一个隐藏标志..。所以当你点击一个问题,它设置了标志,然后当你点击另一个,你必须首先切换标志,然后它将按照预期在第二次点击。
可以这样改进:
$(document).ready(function() {
$('.answer').hide();
$('.main h2').click(function() {
$(this).next('.answer').slideToggle();
});
}); // end readyhttp://jsfiddle.net/wUTaS/1/
发布于 2014-06-09 04:50:36
使用以下代码,请参见注释
<script>
$(document).ready(function() {
$('.answer').hide(); //on page load ...all answers will hide
$('.main h2').click(function()//when you click on any question
{
$(this).next('.answer').toggle();//answer will hide /show
});
}); // end ready
</script>https://stackoverflow.com/questions/24113769
复制相似问题