嘿我写了一个函数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();
});
});
我觉得这应该很容易,但我很遗憾请帮忙
答案 0 :(得分: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);
}
});