gpt4 book ai didi

javascript - 代码重复太多

转载 作者:行者123 更新时间:2023-11-30 07:08:19 24 4
gpt4 key购买 nike

我遇到的问题是,我有很多重复项。我基本上是想显示 1/11 表格,点击底部的表格 (list_row[1-11]),所以当我显示例如表格 2 时,它必须隐藏所有其他表格。

我相信这可以通过循环或其他方式缩短,因为如果我有 100 个表,那么我必须复制和粘贴,这不是聪明的做法。请记住,下面的代码只是显示表 1 到表 3。如何防止这些重复?

// hide the tables by default when page loads
$('#table1').hide();
$('#table2').hide();
$('#table3').hide();
$('#table4').hide();
$('#table5').hide();
$('#table6').hide();
$('#table7').hide();
$('#table8').hide();
$('#table9').hide();
$('#table10').hide();
$('#table11').hide();

// Show Exhaust Temperature diagram

$('#list_row1').on('click',function(){
$('#table1').show();
$('#table2').hide();
$('#table3').hide();
$('#table4').hide();
$('#table5').hide();
$('#table6').hide();
$('#table7').hide();
$('#table8').hide();
$('#table9').hide();
$('#table10').hide();
$('#table11').hide();
});

// Show Cylinder Pressure diagram
$('#list_row2').on('click',function(){
$('#table1').hide();
$('#table2').show();
$('#table3').hide();
$('#table4').hide();
$('#table5').hide();
$('#table6').hide();
$('#table7').hide();
$('#table8').hide();
$('#table9').hide();
$('#table10').hide();
$('#table11').hide();

});

$('#list_row3').on('click',function(){
$('#table1').hide();
$('#table2').hide();
$('#table3').show();
$('#table4').hide();
$('#table5').hide();
$('#table6').hide();
$('#table7').hide();
$('#table8').hide();
$('#table9').hide();
$('#table10').hide();
$('#table11').hide();
});

// Code continues to table11.

最佳答案

将所有表设置为 display: none 然后引入一个 .active 类设置为 display: block(或 display:表,在这种情况下)。然后简单地打开和关闭类:

.active {
display: table;
}
$('#list_row1').on('click', function() {
$('.active').removeClass('active');
$('#table1').addClass('active');
});

然而,为了避免重复,您最好扩展它以将 data-* 属性添加到您的 #list_row/n/ 元素,并处理点击关于这些的事件:

<elem id="list_row1" data-row="1"></elem>
$('[data-row]').on('click', function() {
var row = $(this).attr('data-row');

$('.active').removeClass('active');
$('#table' + row).addClass('active');
});

另请注意,您可以使用逗号链接选择器。而不是使用 $(elem1).hide(); $(elem2).hide() 您可以改为 $(elem1, elem2).hide()

关于javascript - 代码重复太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com