jQuery 显示隐藏相同的 class 并隐藏之前打开的标签
jQuery to show hide same class and hide previously open tag
我已经弄乱了一段时间。我拼凑了我找到的代码,但还没有完全找到完美的解决方案。它几乎可以工作。我正在使用 php 通过向文本字符串的每一行添加 <p>
标记将文本字符串转换为常见问题解答部分。然后我使用 jquery 将 类 添加到每个 <p>
。然后我有 jQuery 隐藏显示切换,因此当单击问题时会显示答案。我有那个工作。我现在需要的是 jQuery 在单击不同的问题时隐藏其他答案。这是我的代码:
<script type="text/javascript">
jQuery(document).ready(function($) {
$ ('#faq p:even').addClass('question');
$ ('#faq p:odd').addClass('answer');
$('.answer').hide();
$('.question').click(function(e){
e.preventDefault();
// hide all span
var $this = $(this).parent().find('.answer');
$(".answer").not($this).hide();
// here is what I want to do
$(this).next(".answer").slideToggle( "slow", function() {
// Animation complete.
});
});
});
</script>
和一些示例 html
<div id="faq">
<p class="question">Question 1</p>
<p class="answer">Answer 1</p>
<p class="question">Question 1</p>
<p class="answer">Answer 1</p>
<p class="question">Question 1</p>
<p class="answer">Answer 1</p>
</div>
整个想法是我可以在 wordpress 编辑器中输入内容并将其变成常见问题解答部分,而无需大量预编码。
您的答案选择器有问题。它按原样选择所有答案。 (如果每个 question/answer 对都包装在一个容器元素中,它就可以工作。)
为什么不直接获取点击问题后的元素?
$('.question').click(function (e) {
var $this = $(this).next('.answer');
$(".answer").not($this).slideUp();
// here is what I want to do
$(this).next(".answer").slideToggle("slow", function () {
// Animation complete.
});
});
我已经弄乱了一段时间。我拼凑了我找到的代码,但还没有完全找到完美的解决方案。它几乎可以工作。我正在使用 php 通过向文本字符串的每一行添加 <p>
标记将文本字符串转换为常见问题解答部分。然后我使用 jquery 将 类 添加到每个 <p>
。然后我有 jQuery 隐藏显示切换,因此当单击问题时会显示答案。我有那个工作。我现在需要的是 jQuery 在单击不同的问题时隐藏其他答案。这是我的代码:
<script type="text/javascript">
jQuery(document).ready(function($) {
$ ('#faq p:even').addClass('question');
$ ('#faq p:odd').addClass('answer');
$('.answer').hide();
$('.question').click(function(e){
e.preventDefault();
// hide all span
var $this = $(this).parent().find('.answer');
$(".answer").not($this).hide();
// here is what I want to do
$(this).next(".answer").slideToggle( "slow", function() {
// Animation complete.
});
});
});
</script>
和一些示例 html
<div id="faq">
<p class="question">Question 1</p>
<p class="answer">Answer 1</p>
<p class="question">Question 1</p>
<p class="answer">Answer 1</p>
<p class="question">Question 1</p>
<p class="answer">Answer 1</p>
</div>
整个想法是我可以在 wordpress 编辑器中输入内容并将其变成常见问题解答部分,而无需大量预编码。
您的答案选择器有问题。它按原样选择所有答案。 (如果每个 question/answer 对都包装在一个容器元素中,它就可以工作。)
为什么不直接获取点击问题后的元素?
$('.question').click(function (e) {
var $this = $(this).next('.answer');
$(".answer").not($this).slideUp();
// here is what I want to do
$(this).next(".answer").slideToggle("slow", function () {
// Animation complete.
});
});