【发布时间】:2012-12-13 23:16:33
【问题描述】:
嘿,我写了一个函数 getNewId,它根据时间戳返回一个随机数 我希望能够在一个空的 [] 中获取该数字,以便当我检查元素并查看代码时,它看起来像这样
name="locations[timestamp_from_function][street]"
这是我正在处理的小提琴
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();
});
});
我觉得这应该很容易,但我迷路了,请帮助
【问题讨论】:
-
不相关,但按钮上的“添加位置”拼写错误
-
你为什么不把它变成一个下划线模板,就像你对
tpl所做的那样? -
@BubbaWoop 好吧,你拼错了“拼写”,所以看来我们有一个拼写警察僵局:)
-
您说您想要一个基于时间戳的随机数,但您似乎只是使用当前时间戳。那不是随机数。
-
你说得对,我说错了对不起,我的意思是我只需要时间戳,但对于每个表格,它应该是一个唯一的数字
标签: javascript underscore.js template-engine