点击特定的div时显示特定的内容JS/jQuery
我有一个常见问题页面,我试图获得一个特定的答案,以显示某个问题被点击时。点击特定的div时显示特定的内容JS/jQuery
这里是一个小提琴:http://jsfiddle.net/hdr6shy9/
下面是代码:
HTML:
<div class="questions">
<div>First Question</div>
<p>Answer to first questions</p>
<div>Second Question</div>
<p>Answer to second Question</p>
<div>Third Question</div>
<p>Answer to third question</p>
</div>
CSS:
.questions div{
cursor:pointer;
margin:10px 0;
}
p{
display:none;
background-color:#f4f4f4;
padding:10px;
}
我想p来根据显示正确的div问题被点击。任何帮助?由于
使用此代码:
$(".questions div").on('click', function() {
$(".questions p").hide();
$(this).next().show();
});
这将显示被点击的div的下一个元素,你要知道,如果有将是另一种元素,那么就会有不同登录(例如使用类,或者使用.next('p')
来确保您仅选择p元素)。
小提琴更新和工作:http://jsfiddle.net/hdr6shy9/8/
真棒,谢谢!如果点击另一个问题,我该如何隐藏它? – Chipe 2014-08-27 16:32:31
你可以在show line之前使用'$(“。questions p”)。hide()'。我现在更新 – 2014-08-27 16:35:27
@Chipe只是更新的代码和小提琴。 – 2014-08-27 16:36:21
您可以使用jQuery为:
$(".questions div").click(function() {
$(this).next().show();
});
这里是在实现这一目标的一个可能的方式小提琴:
$('.question').click(function() {
$(this).next('p').show();
});
我会建议你添加一个id
属性问题div
和答案p
,为什么?也许将来你需要重构你的FAQ页面,这很容易维护。
<div class="questions">
<div id="1">First Question</div>
<p id="a1">Answer to first questions</p>
<div id="2">Second Question</div>
<p id="a2">Answer to second Question</p>
<div id="3">Third Question</div>
<p id="a3">Answer to third question</p>
</div>
$('.questions div').click(function(){
var qid = $(this).attr('id');
$('#a'+qid).show();
});
如果将来你改变你的HTML这样的:
<div class="questions">
<div id="1">First Question</div>
<div id="2">Second Question</div>
<div id="3">Third Question</div>
</div>
<div class="answers">
<p id="a1">Answer to first questions</p>
<p id="a2">Answer to second Question</p>
<p id="a3">Answer to third question</p>
</div>
同一个JavaScript代码将工作。
否则,@ lolkidoki解决方案就是您所需要的。
差不太多,这里有一个办法:
$('.question').click(function() {
$(this).next('p').show();
});
看所有的高声望用户排队编写代码是免费的。惊人。 – 2014-08-27 16:29:26
这是一件坏事吗? – Chipe 2014-08-27 16:34:56
是的。该网站的目的是建立一个对程序员来说很有用的问题和答案库;这不仅仅是专门帮助你。你在这里有什么问题?没有一个。什么是要解决的问题?问题是“我没有代码”。如何解决这个问题将帮助任何人**其他**?它帮助你,很棒,但这不是网站的目的。查看http://stackoverflow.com/help/how-to-ask。你在这里得到了答案,但它最终是混乱的,因为问题和答案通常不是有用的。 – 2014-08-27 16:41:37