我正在尝试获取手风琴组名称,如果组名相同,但条件不起作用,我在这里做错了,有人请检查并建议:
<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
答案 0 :(得分:2)
您需要存储在变量中,并且该变量应在函数外部声明。
在下面的示例中,我们有3个按钮,前2个按钮具有相同的组,最后一个具有不同的组名。
情景1:
情景2:
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;