jQuery:生成" name"动态属性数组

时间:2016-07-20 07:30:49

标签: javascript jquery arrays loops name-attribute

我有一个这样的表格:

<form>
  <div class="repeatable">
    <div class="repeatable">
      <div class="repeatable">
        <input name="level_three">
        <input name="inner_three">
        <a>+</a>
      </div>
      <input name="level_two">
      <a>+</a>
    </div>
    <input name="level_one">
    <a>+</a>
  </div>
</form>

加号克隆距离自身最近的整个repeatable。我想要一个jQuery函数来遍历repeatable并使输入名称成为这样的数组:

<form>
  <div class="repeatable">
    <div class="repeatable">
      <div class="repeatable">
        <input name="level_three[0][0]">
        <input name="inner_three[0][0]">
        <a>+</a>
      </div>
      <div class="repeatable">
        <input name="level_three[0][1]">
        <input name="inner_three[0][1]">
        <a>+</a>
      </div>
      <input name="level_two[0]">
      <a>+</a>
    </div>
    <div class="repeatable">
      <div class="repeatable">
        <input name="level_three[1][0]">
        <input name="inner_three[1][0]">
        <a>+</a>
      </div>
      <div class="repeatable">
        <input name="level_three[1][1]">
        <input name="inner_three[1][1]">
        <a>+</a>
      </div>
      <div class="repeatable">
        <input name="level_three[1][2]">
        <input name="inner_three[1][2]">
        <a>+</a>
      </div>
      <input name="level_two[1]">
      <a>+</a>
    </div>
    <input name="level_one">
    <a>+</a>
  </div>
</form>

我们可能有repeatable个。在该示例中,总共有3个级别。它可能是1,2,3,4或任何数字。

1 个答案:

答案 0 :(得分:0)

$(function(){

  $('form > .repeatable').each(function(l1_Index, l1_elem){
      $('> .repeatable', l1_elem).each(function(l2_Index, l2_elem){
          $('> .repeatable', l2_elem).each(function(l3_Index, l3_elem){
              $('input', l3_elem).each(function(input_Index, input_elem){

                var computed = (input_Index === 0 ? 'level_three' : 'inner_three') + 
                      '[' + l1_Index + ']' + '[' + l2_Index + ']' ;

                $(input_elem).attr('name', computed);

              });
          });
      });
  });
});

请参阅此处的代码示例https://jsbin.com/colocunoqo/edit?html,js,output

P.S。像棱角分明的任何模板化的lib都会让你变得非常容易

编辑:使用递归https://jsbin.com/sisivucaxe/edit?html,js,output