我需要在用户输入时创建带有动态标签的动态字段,更明确地说:
我要求用户选择一个日期范围,并根据该日期范围为每个日期创建标签和输入字段
为此,我所做的是在输入表单字段的更改事件上调用 AJAX
函数,并根据我在 php
函数和 echo< 中处理的输入
将模板添加到页面并将其附加到如下表单中
$('#setdates').click(function() {
startDate = document.getElementById('event-start_date').value;
endDate = document.getElementById('event-end_date').value;
$.ajax({
url: "showtimings",
type: 'POST',
data:{
'startdate': startDate,
'enddate': endDate,
},
success: function(result){
$("#optionTemplate").html(result);
}});
});
下面是我根据输入从函数返回的模板。此模板乘以用户输入的时间数
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<label>Date is Dynamic</label>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-4">
<select class="form-control" id="starttime0">
<option>00:00</option>
<option>01:00</option>
<option>02:00</option>
<option>03:00</option>
<option>04:00</option>
</select>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-4">
<select class="form-control" id="starttime0">
<option>00:00</option>
<option>01:00</option>
<option>02:00</option>
<option>03:00</option>
<option>04:00</option>
</select>
</div>
</div>
然后根据我从 php
函数回显 html
模板并将其附加到页面。
我想知道这是一个好的做法还是有其他方法可以提高效率?
即使是现在,返回数据并将其附加到表单也需要很长时间,所以我认为这是因为调用了函数。有没有其他方法可以让它快速处理?
最佳答案
[编辑]
这是一个由他自己(在普通 JS 中)生成一组字段的版本。我不完全知道你的需要,所以你必须调整它以获得你想要的东西
function genTemplate(startDate, endDate) {
var buffer = '';
startDate = new Date(startDate).getTime();
endDate = new Date(endDate).getTime();
day = new Date(startDate);
var timediff = endDate - startDate;
nbDay = Math.floor(timediff / (1000*60*60*24));
var i;
for(i = 0; i < nbDay; i++) {
day.setDate(day.getDate() + 1);
buffer = buffer +
'<div class="row">'+
'<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">'+
'<label>'+day.toDateString()+'</label>'+
'</div>'+
'<div class="col-lg-2 col-md-2 col-sm-2 col-xs-4">'+
'<select class="form-control" id="starttime0">'+
'<option>00:00</option>'+
'<option>01:00</option>'+
'<option>02:00</option>'+
'<option>03:00</option>'+
'<option>04:00</option>'+
'</select>'+
'</div>'+
'<div class="col-lg-2 col-md-2 col-sm-2 col-xs-4">'+
'<select class="form-control" id="starttime0">'+
'<option>00:00</option>'+
'<option>01:00</option>'+
'<option>02:00</option>'+
'<option>03:00</option>'+
'<option>04:00</option>'+
'</select>'+
'</div>'+
'</div>';
}
return buffer;
}
function f() {
startDate = document.getElementById('event-start_date').value;
endDate = document.getElementById('event-end_date').value;
optionTemplate = document.getElementById("optionTemplate");
optionTemplate.innerHTML = genTemplate(startDate, endDate);
}
start <input id="event-start_date" value="2015-11-10"><br>
end <input id="event-end_date" value="2015-11-15"><br>
<button onclick="f()">Run</button><br>
<hr>
<div id="optionTemplate">
</div>
关于javascript - 在 AJAX 调用上返回 html 表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33861061/