Jquery 如何在具有多个类的表中按计数重命名表行
这是我的设置,我有一个表格,它是表单的一部分,有一组包含多个类的行Jquery 如何在具有多个类的表中按计数重命名表行,jquery,Jquery,这是我的设置,我有一个表格,它是表单的一部分,有一组包含多个类的行 <table> <tr class='class1'><!--all rows will host inputs and a button that can delete this row--></tr> <!--the first row of a class will contain an add row button, and a set of headers--&
<table>
<tr class='class1'><!--all rows will host inputs and a button that can delete this row--></tr>
<!--the first row of a class will contain an add row button, and a set of headers-->
<!--there are about 4 rows for each class-->
<tr class='class2'></tr>
<tr class='class3'></tr>
<tr class='class4'></tr>
<table>
特定类的行将对用户隐藏/不可见,直到用户按下按钮显示特定类的表行。用户可以通过按按钮添加行和删除特定行。所有输入都有名称,应自动生成
但是,我希望保持命名约定的一致性,保持名称范围的可管理性 我开发了一个delete函数,该函数计算行数,并根据其位置重命名所有输入,但该方法仅适用于没有类的表。 这是我所拥有的
/*
inputs would look like this
<input class="class1" name="input11"></input>
<input class="class2" name="input21"></input>
*/
<script>
$(".class1").each(function(){
var row_index = $(this).parent().parent().index();
var newName = "input1"+row_index;
$(this).attr("name",newName);
});
</script>
/*
输入应该是这样的
*/
$(“.class1”).each(function(){
var row_index=$(this.parent().parent().index();
var newName=“input1”+行索引;
$(this.attr(“name”,newName);
});
我曾考虑使用.count()命令,但它不会提供我想要的增量命名
我想防止输入名称重复的情况,并防止输入名称之间存在间隙的情况i、 e.存在名称为input13和input15的输入,但input14不存在。您可以循环文档的匹配元素,并将名称与索引连接起来:
var z = 1;
$.each($('.class1:nth-child(n)'),function(){
var newName = 'Name'+z;
$(this).attr('name',newName);
z++;
});
您是否意识到元素将根据其在父元素中的位置在兄弟元素中建立索引?您可以使用选择器来获取一个特定的选择器,而不需要类?看起来您的代码过于复杂,没有充分使用上下文选择器potential@Taplar,谢谢你的评论,但我想你误解了我的问题。因为我需要用class=“class1”查找并循环遍历每个输入,并将它们重命名为循环结构的一部分,这样就不会出现不一致的情况。我不会误解这一点。我的意思是你根本不需要它,你可能想在这里增加z。