在我的项目中,我必须检查时间表时间的可用性,方法是插入一个应包含两个值作为文本的按钮。一天从8点开始到18点结束,每天都有时段。我有一个 JSON 数组,其中包含当天的所有 session ,每个 session 都有开始时间和结束时间,因此当我找到任何时间空间时,我想在 html 中附加一个按钮。该按钮将包含一些文本(例如:8->10)以及一个 onClick
方法,该方法将带我到另一个函数。这是一些代码,我希望它能让我的问题更容易理解:
function evenement(id)
{
$.ajax({
url : "<?php echo site_url('index.php/salle/evenement/')?>/" + id,
type: "GET",
dataType: "JSON",
success : function(data)
{ var start_date =8;
var end_date =18;
var buttons ="";
data.forEach(function(element, index, array)
{
for (var i = start_date; i < end_date; i++) {
if (element.date_debut == i) {i=element.date_fin;}
if (element.date_debut != i) {buttons +="<button>"+i+"->"+element[index+1].date_fin+"</button>";}
}
}
);
$('.modal-title').text('Disponibilité');
$('#corps').html(buttons);
$('#groupe_modal').modal('show');
},
});
}
我的问题是在处理当前元素时无法到达下一个元素。数据是我在 ajax 函数中收到的参数,这段代码只是为了让我清楚自己,我将其编写在项目的不同部分中。谢谢!
最佳答案
forEach
callback函数有3个参数,function(element,index,array)
`element` The current element being processed in the array.
`index` The index of the current element being processed in the array.
`array` The array that forEach() is being applied to.
因此,如果您向函数添加第二个参数(即索引),那么您可以轻松访问下一个 data[index + 1]
(或上一个 data[index - 1] ]
) 带有它的项目
Don't forget to properly check that you are not at the last (of first for previous) element when using it
根据问题编辑进行更新
如果将第二个和第三个参数添加到函数中,则 index
和 array
为 forEach()
被应用到,然后您可以访问下一个(或上一个)项目,如下所示:
array[index + 1] //next
array[index - 1] //previous
function evenement(id)
{
$.ajax({
url : "<?php echo site_url('index.php/salle/evenement/')?>/" + id,
type: "GET",
dataType: "JSON",
success : function(data)
{
var start_date =8;
var end_date =18;
var buttons ="";
data.forEach(function(element, index, array)
{
for (var i = start_date; i < end_date; i++) {
if (element.date_debut == i) {i=element.date_fin;}
if (element.date_debut != i) {buttons +="<button>"+i+"->"+array[index+1].date_fin+"</button>";}
}
});
$('.modal-title').text('Disponibilité');
$('#corps').html(buttons);
$('#groupe_modal').modal('show');
}
});
}
关于javascript - 与 foreach javascript 中的下一个元素进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43443887/