我希望我网页上的表格能够响应。一旦页面宽度低于某个阈值,他们就会自动将其表示为手风琴。我从this页面提取了手风琴的示例代码。
我现在的问题是整个表格行变成了一个触发相应折叠/展开的按钮。我如何重新连接js
以使<i>
元素负责接收点击事件而不是<tr>
元素?
我想要这种行为的原因非常简单:我的表包含几个input
元素,这一点不能再使用了,因为只要点击任何这些输入,表就会折回。
这是我的尝试。但是,它会折叠/展开每一行而不是用户点击的那一行:
trAcc.find('i').click(function () {
if (trAcc.hasClass('accordion-opened')) {
trAcc
.animate({ maxHeight: '50px' }, 200)
.removeClass('accordion-opened');
$(this).text('+');
} else {
trAcc
.animate({ maxHeight: '1000px' }, 400)
.addClass('accordion-opened');
$(this).text('-');
}
});
这是原始fiddle。
答案 0 :(得分:1)
由于我是jQuery
的新手,我目前对API知之甚少。但是,我偶然发现了parent方法。使用它,问题变得非常简单,我的解决方案归结为:
trAcc.find('i').click(function () {
if ($(this).parent('tr').hasClass('accordion-opened')) {
$(this).parent('tr')
.animate({ maxHeight: '50px' }, 200)
.removeClass('accordion-opened');
$(this).text('+');
} else {
$(this).parent('tr')
.animate({ maxHeight: '1000px' }, 400)
.addClass('accordion-opened');
$(this).text('-');
}
});
答案 1 :(得分:1)
我将原来的jsFiddle代码修改为this。
trAcc.append('<i class="icon-accordion">+</i>');
$('.icon-accordion').on('click', function (e) {
e.stopImmediatePropagation();
if ($(this).parent().hasClass('accordion-opened')) {
$(this)
.parent()
.animate({maxHeight: '60px'}, 200)
.removeClass('accordion-opened')
.end()
.text('+');
} else {
$(this)
.parent()
.animate({maxHeight: '1000px'}, 400)
.addClass('accordion-opened')
.end()
.text('-');
}
});