0

嘿,我写了一个函数 getNewId,它根据时间戳返回一个随机数

名称="位置[timestamp_from_function][街道]"

这是我在http://jsfiddle.net/d0okie0612/22cTn/上工作的小提琴

这是我的html

   <div id="container">
   <div id="top_form">
   <form>
    Street: <input class="street" name="locations[][street]" id="form_element" type="text">  <br><br>
       City: <input class="city" name="locations[][city]" id="form_element" type="text">
      <select>
        <option value=" ">State</option>
        <option value="ca">CA</option>
        <option value="az">AZ</option>
        <option value="de">DE</option>
        </select>
        Zip: <input name="locations[][zipcode]" type="text"><br /><br />
     </form>
   </div>
  </div>

 <br />
 <a href="#" id="awsomeButton">+ Add Location</a>
  <br />


提交

这是脚本

     var tpl = ""
     + "<div id='location_div_<%= id %>'><h1>My Location #<%= id %></h1></div>";

      var newId = new Date().getTime();
      var template = _.template(tpl);
       var compiled = template({id: newId});

       var addedForm = "<div id='added_form'>"
         + "<a href='#' class='close_btn'>x</a>"
         + "Street: <input name='locations[][street]' type='text'>"
          + "<br /><br />"
           + "City: <input name='locations[][city]' type='text'>"
           + "<select>"
           + "<option value=' '>State</option>"
           + "</select>"
           + "Zip: <input name='locations[][zipcode]' type='text'>"
            + "</div>"


           function getNewId() {
           var newId = new Date().getTime();
           return newId;
             }

            var myArray = [];
            $('#awsomeButton').on('click', function(e) {
            $(addedForm).hide().appendTo('form').fadeIn('slow');

            });


           $('.close_btn').live('click', function (e) {
           e.preventDefault();
           $(this).parents('div#added_form:first').fadeOut('slow', function() {
          $(this).remove();    

        });
         });

我觉得这应该很容易,但我迷路了,请帮忙

​ ​</p>

4

1 回答 1

0
$("#added_form input[name^=locations\\[\\]]").each(function(input){
   var name = input.attr("name");
   var match = name.match(/^locations\[\]\[(.*)\]$/)
   if(match.length > 1) {
      var newName = "locations["+getNewId()+"]["+match[1]+"]";
      input.attr("name", newName);
   }
});
于 2012-12-13T23:28:04.247 回答