当用户提供输入时,我需要使用动态标签创建动态字段,以便更明确:
我要求用户选择日期范围,并根据该日期范围我想为每个日期创建标签和输入字段
为此我所做的就是在输入表单字段的更改事件上调用AJAX
函数,并根据php
函数中的输入i进程和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>
然后根据我的回复来自html
函数的php
模板并将其附加到页面。
我想知道这是一个很好的做法还是有其他方法可以让它更有效率?
即使是现在,它需要花费大量时间来返回数据并将其附加到表单中,因此我认为它是因为对函数的调用。有没有其他方法可以让它快速处理?
答案 0 :(得分:1)
[编辑]
这是一个自己(在vanilla 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>