我有未知数量的链接和 div 对,我根据点击隐藏和显示它们。我知道必须有更好的方法来做到这一点 - 重构我的代码以获取数字部分并从 01 到 N 循环它们。
虽然下面的示例有 4 对 anchor 标记和 div,但数量可以是 1 到 100(或更多)之间的任意值
HTML 标记:
<a class="bioImg bioImg01"></a>
<a class="bioImg bioImg02"></a>
<a class="bioImg bioImg03"></a>
<div class="bioContainer bioContainer01">
</div>
<div class="bioContainer bioContainer02">
</div>
<div class="bioContainer bioContainer03">
</div>
<a class="bioImg bioImg04"></a>
<div class="bioContainer bioContainer04"></div>
JavaScript (jQuery): 这是我知道效率低下的部分 - 只是没有足够的经验和词汇来正确地完成它
// Click events for Bio page
if ($('.bioImg').length > 0) {
$('.bioImg').click(function() {
$('.bioImg').removeClass('active');
$(this).addClass('active');
});
}
if ($('.bioContainer').length > 0) {
$('.bioImg01').click(function() {
$('.bioContainer').hide();
$('.bioContainer01').fadeToggle();
});
}
if ($('.bioContainer').length > 0) {
$('.bioImg02').click(function() {
$('.bioContainer').hide();
$('.bioContainer02').fadeToggle();
});
}
if ($('.bioContainer').length > 0) {
$('.bioImg03').click(function() {
$('.bioContainer').hide();
$('.bioContainer03').fadeToggle();
});
}
if ($('.bioContainer').length > 0) {
$('.bioImg04').click(function() {
$('.bioContainer').hide();
$('.bioContainer04').fadeToggle();
});
}
最佳答案
您可以使用索引将这些组匹配在一起。除非您有特殊的 CSS,否则很少需要为一组相同类型元素中的每个元素使用唯一的类名称
var $bioImg = $('.bioImg').click(function() {
// get index of current bioImg within collection
var index = $bioImg.index(this);
$bioImg.removeClass('active');
$(this).addClass('active');
// hide all containers and fade in matching indexed one
$('.bioContainer').hide().eq(index).fadeIn();
});
关于javascript - 重构 jQuery 以影响 N 个 anchor 和 div 对的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40456749/