如何使用foreach从html标签中获取动态值,并将其保存到momentObj的jquery变量中



老实说,我不确定如何为此制作合适的标题,但基本上我试图从span标签中提取元素,该标签动态来自 foreach 数据库的id=duration,并使用它在倒计时的持续时间内显示计时器.js,但我感到困惑,因为它只提取第一个 foreach 值而不是其余值,因为它具有我认为相同的 id。 这是视图

<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<?php foreach($status as $row): ?>
<tr>
<td><?php   echo $row->room_name;                         
?></td>
<td>                            
<?php if($row->user_name!=null)
{
echo $row->user_name;

}else{ echo "Available"; }; 
?>
</td>
<td>
<?php if($row->start_time!=null)
{
echo $row->start_time;
}else{  echo "Available";}; 
?>
</td>
<td><span class="timer"><span id="duration"><?php if($row->start_time!=null)
{
echo $row->start_time;
}else{  echo "Available";}; 
?></span></span></td>
<td>
<?php if($row->status!=null)
{
echo $row->status;
}else{ echo "Available";}; 
?>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<script src="assets/home/js/jquery.min.js"></script>
<script src="assets/js/moment.min.js"></script>
<script src="assets/js/countdown.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/dynamic-marquee@1"></script>
<script>
var times = $('#duration').text();
function update() {

var addDay = /*$('#duration')*/ moment(times);
$('#clock').html(moment().format('H:mm:ss')+ ' WIB');
$('.timer').html(addDay.countdown().toString());
console.log(addDay);
console.log(times);
}

setInterval(update, 1000);
$(window).on("load resize ", function() {
var scrollWidth = $('.tbl-content').width() - $('.tbl-content table').width();
$('.tbl-header').css({'padding-right':scrollWidth});
}).resize();
</script>
<script>
(function(){var countdown,moment,ref,ref1,slice=[].slice;countdown=(ref=typeof require==="function"?require("countdown"):void 0)!=null?ref:this.countdown;moment=(ref1=typeof require==="function"?require("moment"):void 0)!=null?ref1:this.moment;moment.fn.countdown=function(){var args,other;other=arguments[0],args=2<=arguments.length?slice.call(arguments,1):[];return countdown.apply(null,[this.toDate(),moment(other).toDate()].concat(slice.call(args)))}}).call(this);
</script>

由于 ID 必须是唯一的,因此只能使用通用类名。此外,您需要更改每个实例,在这种情况下,您可以使用text(function)内部将遍历每个实例。

然后,您还需要启动初始start_time可以使用data-属性执行。现在,无论何时调用update()都可以从该属性中获取初始值并基于它进行计算。

我没有制造一些日期/时间,而是创建了一个非常简单的案例,在调用时只添加一个

function update(){
console.log('Update called')
$('.timer').text(function(){
const start = $(this).data('start');
// do calculations based on start value
let newVal = start + 1;
return newVal
});
}
// only calling it once for simplicity
setTimeout(update, 2000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
<thead>
<tr>
<th>Room</th>
<th>Start</th>
</thead>
<tbody>
<tr>
<td>Room 1</td>
<td>
<span class="timer" data-start="1">1</span>
</td>
</tr>
<tr>
<td>Room 2</td>
<td>
<span class="timer" data-start="2">2</span>
</td>
</tr>
</tbody>
</table>

最新更新