如何分别触发每个类

时间:2013-11-22 01:55:28

标签: javascript jquery jquery-ui jquery-selectors slide

下面是我的jQuery幻灯片开关代码。非常简单的代码,但我不能单独触发每个。当我点击一个时,一切都将被同时触发。我知道它适用于所有同类课程,但我无法理解我将如何处理。我有很多这样的div。

HTML

<div class="answerarea">
  <div class="answer"><a class="ans">go</a></div>
  <div class="answertxt"> show this</div>
</div>
<div class="answerarea">
  <div class="answer"><a class="ans">go</a></div>
  <div class="answertxt"> show this</div>
</div>
<div class="answerarea">
  <div class="answer"><a class="ans">go</a></div>
  <div class="answertxt"> show this</div>
</div>
<div class="answerarea">
  <div class="answer"><a class="ans">go</a></div>
  <div class="answertxt"> show this</div>
</div>

CSS

.answerarea {
    float: left;
    width: 350px;
    margin:20px;
}
.ans {
    padding: 5px;
    background-color: #990;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    cursor:pointer;
}
.answertxt {
    background-color: #06C;
    display:none;
    color: #FFF;
    padding: 2px;
    float: left;
}
.answer {
    float: left;
}

JS

$(document).ready(function(){
        $('.ans').click(function (e) {
    e.stopPropagation();
    if($('.answertxt').hasClass('visible')) {
        $('.answertxt').stop().hide('slide', {direction: 'left'}, 500).removeClass('visible');
    } else {
        $('.answertxt').stop().show('slide', {direction: 'left'}, 500).addClass('visible');
    }
   });
});

demo http://jsfiddle.net/JSkZU/

N.B。 admin / mod我很抱歉没有正确的主题。实际上我不明白哪个主题适合这个问题。你可以解决。感谢

1 个答案:

答案 0 :(得分:1)

尝试使您的选择器更具体,您将选择所有选择器。

 $('.ans').click(function (e) {
        e.stopPropagation();
        var $this = $(this); //this represent the clicked element
        //Get to the closest/parent and select next and do a toggle and toggleclass on it
        $this.parent().next().stop().toggle('slide', {
            direction: 'left'
        }, 500).toggleClass('visible');

    });

<强> Demo

.toggle()将切换元素的当前状态,.toggleClass将根据其缺席​​/存在添加/删除该类。

为了折叠其他人,你可以这样做:

$(document).ready(function () {
    $('.ans').click(function (e) {
        e.stopPropagation(); //did you mean e.preventDefault();
        var $this = $(this), $answerTxt = $this.closest('.answer').next();
        $answerTxt.add($('.answertxt.visible')).stop().toggle('slide', {
            direction: 'left'
        }, 500).toggleClass('visible');
    });
});

<强> Demo

相关问题