如何处理点击的div并滑动其邻居

时间:2014-06-19 11:49:14

标签: jquery jquery-selectors

尝试制作滑动项目。一件物品一切正常。但我需要添加多个项目,它们都会打开。我需要处理点击并只打开一个。

http://jsbin.com/xaxeregu/5/edit

JQUERY:

$('.faqTitle').click(function () {
    $('.faqAnswer').slideToggle('fast');
});

HTML:

<div class="faqItem">
    <div class="faqTitle">Here is my title</div>
    <div class="faqAnswer">here is an answer here is an answer here is an answer here is an answer here is an answer here is an answer here is an answer here is an answer</div>
</div>
<div class="faqItem">
    <div class="faqTitle">Here is my title</div>
    <div class="faqAnswer">here is an answer here is an answer here is an answer here is an answer here is an answer here is an answer here is an answer here is an answer</div>
</div>

CSS:

.faqItem {
    background-color: white;
}
.faqAnswer {
    display:none;
}
body {
    background-color: grey;
}

5 个答案:

答案 0 :(得分:3)

您只定位.faqAnswer,其目标是所有具有类名.faqAnswer的div,但如果您想定位下一次出现的结果目标,则可以使用$(this)其中$(this)指的是点击的[当前]元素。

试试这个,

$('.faqTitle').click(function(event){
  $(this).next(".faqAnswer").slideToggle('fast');  
});

$('.faqTitle').click(function(event){
  $(this).closest('div.faqItem').find('.faqAnswer').slideToggle('fast');
});

Demo

<强>文档

答案 1 :(得分:2)

你可以点击元素的父元素,然后使用find找到它的子元素..可能是你的html更改的好方法,你可以改用.parents('.faqItem')

$('.faqTitle').click(function(event){
  $(this).parent().find('.faqAnswer').slideToggle('fast');
});

答案 2 :(得分:2)

尝试

$('.faqTitle').click(function() {
  $(this).next('.faqAnswer')..slideToggle('fast')
}

答案 3 :(得分:2)

$('.faqTitle').click(function(event){
  $(this).next(".faqAnswer").slideToggle('fast'); 
});

使用next()查找下一个faqAnswer

Demo Fiddle

答案 4 :(得分:2)

替换这行代码

$('.faqAnswer').slideToggle('fast');

$(this).parent().find('.faqAnswer').slideToggle('fast');