2012-12-13 46 views
0

嘿我寫了一個函數getNewId,返回一個基於時間戳的隨機數 我希望能夠在空[]中獲得該數字,以便當我檢查元素看看它看起來像這樣如何讓函數進入我的空[]

名= 「位置[timestamp_from_function] [街]」

這裏的代碼在
http://jsfiddle.net/d0okie0612/22cTn/

在這裏工作的小提琴IM是我的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();  

     }); 
     }); 

我還挺想這應該是容易的,但在失去了IM,請幫助

+0

無關,但你拼寫'add location'按鈕錯誤 – Luke

+0

爲什麼你不把它做成一個下劃線模板,就像你用'tpl'完成的那樣? – Bergi

+0

@BubbaWoop那麼你拼寫錯了,所以它似乎我們有一個拼寫警察對峙:) –

回答

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); 
    } 
});