我正在尝试创建一个与此处类似的常见问题解答页面:https://www.harrys.com/help 我想创建效果,点击问题会显示答案。
我的代码可以在这里看到:http://jsfiddle.net/8UVAf/1/
有人可以告诉我为什么我的javascript无效吗?我意识到我结合了jQuery和Javascript,但我在某处读到它应该编译得很好。
HTML:
<div class="questions-answer-block">
<p class="question">This is a Question?</p>
<p id="answer" class="hideinit">Here is the Answer</p>
</div>
<div class="questions-answer-block">
<p class="question">This is a Question?</p>
<p id="answer" class="hideinit">Here is the Answerdadawdawdawdawdawdawdawdwadawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawd</p>
</div>
JS:
$(".question").click(function (argument) {
if(document.getElementById("answer").className.match(/(?:^|\s)hideinit(?!\S)/)) {
document.getElementByID("answer").className = "display";
}
});
答案 0 :(得分:1)
基本上你的Javascript可以缩短为:
$(".question").click(function(argument) {
$(this).parent().find(".answer").removeClass("hideinit").addClass("display");
});
为了完成这项工作,你需要做的唯一事情就是让question
成为一个类而不是一个id。看起来像是:
<p class="answer hideinit">the answer</p>
<强> See the fiddle here 强>
编辑:添加隐藏/显示
要使其隐藏并按预期显示,您需要更新代码以在隐藏和显示之前检查当前类。看起来像是:
$(".question").click(function(argument) {
var el = $(this).parent().find(".answer");
if (el.hasClass("display")) {
el.removeClass("display").addClass("hideinit");
} else {
el.removeClass("hideinit").addClass("display");
}
});
<强> See the fiddle here 强>
答案 1 :(得分:0)
嗯,首先,在你的JSFiddle中你没有包含jQuery库。我调整了你的代码,我认为这就是你想要的:
$(".question").click(function() {
$(this).siblings().toggle();
});
答案 2 :(得分:0)
请在您的JSFiddle中查看您的包含,因为您链接的版本不包括jQuery库。您还应该清理多个id
引用(因为这是无效的HTML并且会导致一些问题)。
除了这些问题之外,您可以使用jQuery的.next()
方法来帮助您解决这个特定问题:
$(".question").click(function (argument) {
$(this).next(".hideinit").removeClass("hideinit").addClass("display");
});
答案 3 :(得分:0)
$(".question").on('click',function() {
$(this).next().toggle();
});