在JQuery nextAll()中使用更改变量

时间:2009-11-05 17:44:41

标签: jquery regex variables

使用jquery,我正在动态添加行。为此,我正在复制表的第一个,然后使用一些正则表达式,我将名称和有时ID从“column_name [0]”更改为“column_name [1]”。这是我正在使用的正则表达式:

  newRow = newRow.replace(new RegExp("\\[[0-9]+][\"\']", "gm"), "[" + $("#rowNum").val() + "]\"");

这很好。

我还添加了动态删除此行的链接。此删除链接在单击时执行以下JQuery:

$(this).parents(\"tr.deletable\").remove();

这也很好。

现在,我的问题是用户添加3行,然后删除第一行。我希望后两行减少其索引号。例如,column_name [2]将更改为column_name [1]。我该怎么做呢?这是我到目前为止所尝试的内容:

$(this).parents("tr.deletable").nextAll().html().replace(new RegExp("\\[[0-9]+][\"\']", "gm"), "[" + i + "]\"");

我设置为50只是为了看它是否成功地将其作为新索引,但事实并非如此。我没有想通过顺利得到减少的价值。上面的代码不起作用。

有没有人对如何做到这一点有任何建议?

至于为什么我需要这样做,这是因为我正在使用Java Struts,它要求所有表单元素在末尾都有一个带有适当索引的名称。

2 个答案:

答案 0 :(得分:0)

你可以再向上一层DOM树,然后从那里开始:

$(this).parents("tr.deletable").parent().find("tr.deletable").each();

您需要存储已删除行的索引。

var deletedIndex = parseInt($(this).attr("id").split("[")[1].split("]")[0]); // there's probably a better way to do this

在每个内部,处理您可能需要的行以减少使用此函数的索引。

function() {
  var curIndex = parseInt($(this).attr("id").split("[")[1].split("]")[0]);
  if (curIndex  > deletedIndex) {
    $(this).attr("id", "column_name[" + (curIndex - 1) + "]");
  }
}

所以,总结一下:

// get index of row deleted
var deletedIndex = parseInt($(this).attr("id").split("[")[1].split("]")[0]);

// loop through deleted items' siblings
$(this).parents("tr.deletable").parent().find("tr").each(function() {
  var curIndex = parseInt($(this).attr("id").split("[")[1].split("]")[0]);
  if (curIndex  > deletedIndex) {
    $(this).attr("id", "column_name[" + (curIndex - 1) + "]");
  }
});

此外,可能有更好的方法来循环删除行的兄弟姐妹。像:

var curSib = $(this).next("tr.deletable");
while (curSib.length > 0) {
  var curIndex = parseInt(curSib.attr("id").split("[")[1].split("]")[0]);
  if (curIndex  > deletedIndex) {
    curSib.attr("id", "column_name[" + (curIndex - 1) + "]");
  }
  curSib = curSib.next("tr.deletable");
}

我没有测试这段代码,但我认为你应该明白这个想法。

答案 1 :(得分:0)

我认为最好的方法是让多个输入具有name column_name,然后仅在提交表单时附加[i]。试试这个:

$("#Form").submit(function()
{
    $("input[name=column_name]",this).each(function(index)
    {
        var name = "column_name["+index+"]";
        $(this).attr("name",name);
    });
}