如果手风琴组ID相同 - jQuery

时间:2018-01-25 07:30:02

标签: jquery

我正在尝试获取手风琴组名称,如果组名相同,但条件不起作用,我在这里做错了,有人请检查并建议:

<div class="ab-Accordion ab-Accordion--block">
    <button id="test" type="button" class="Accordion-label js-Accordion" data-accordion-group="contact" role="tab" data-event-type="Accordion" data-event-details="Accordion" aria-selected="false">Accordion Title</button>
</div>

$(".ab-Accordion").bind('click',function(e){
    var accorgrpName = $(this).children().attr('data-accordion-group');
    //the above line return the group name in console correctly
    if ($(this).children().attr('data-accordion-group') == accorgrpName){
        console.log("this is same group - do something");
    }
});

此代码在条件下无法正常工作。

TIA

1 个答案:

答案 0 :(得分:2)

您需要存储在变量中,并且该变量应在函数外部声明。

在下面的示例中,我们有3个按钮,前2个按钮具有相同的组,最后一个具有不同的组名。

情景1:

  • 点击第一个按钮
  • 现在点击第二个按钮(你应该看到 &#39;这是同一群体 - 做点什么&#39;)

情景2:

  • 点击第一个按钮
  • 现在点击第三个按钮(你应该看到 &#39;不同的小组&#39;)

&#13;
&#13;
var accorgrpName = '';
$(".ab-Accordion").bind('click', function(e) {
  if (accorgrpName != '') {
    //the above line return the group name in console correctly
    if ($(this).children().attr('data-accordion-group') == accorgrpName) {
      console.log("this is same group - do something");
    } else {
      console.log('different group');
    }
  } else {
    console.log('This is the first click.. now click some other button..')
  }
  accorgrpName = $(this).children().attr('data-accordion-group');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ab-Accordion ab-Accordion--block">
  <button id="test" type="button" class="Accordion-label js-Accordion" data-accordion-group="contact" role="tab" data-event-type="Accordion" data-event-details="Accordion" aria-selected="false">Accordion Title</button>
</div>
<div class="ab-Accordion ab-Accordion--block">
  <button id="test" type="button" class="Accordion-label js-Accordion" data-accordion-group="contact" role="tab" data-event-type="Accordion" data-event-details="Accordion" aria-selected="false">Accordion with same group</button>
</div>
<div class="ab-Accordion ab-Accordion--block">
  <button id="test" type="button" class="Accordion-label js-Accordion" data-accordion-group="contact-1" role="tab" data-event-type="Accordion" data-event-details="Accordion" aria-selected="false">Accordion with different group</button>
</div>
&#13;
&#13;
&#13;