2 回答

TA貢獻1851條經(jīng)驗 獲得超3個贊
您有一些嵌套問題(腳本標記需要退出for循環(huán)),重復(fù)的id和不正確的計時系統(tǒng)。如果您需要將事情更新為實時,請使用時間戳記和系統(tǒng)時鐘來確定實際剩余時間。
首先,向您的實體添加方法以獲取到期時間戳(以秒為單位)
class Voiture
{
...
public function getExpiresAt()
{
$gareele = $this->getGareele();
$expires = clone $gareele;
$expires->modify('+' . $this->getTime() . ' min');
return $expires->format('U');
}
}
然后在模板中,將計時器范圍更改為具有class="timer"(不需要id),并添加帶有過期時間戳記的data屬性。該腳本將遍歷所有.timers并更新文本以反映該時間點的剩余天數(shù),小時數(shù),分鐘數(shù)和秒數(shù)。在這里,我通過使用setTimeout()函數(shù)內(nèi)部每100毫秒更新一次文本。
{% extends 'Agent/Baseagent.html.twig' %}
{% block title %}Parking index{% endblock %}
{% block body %}
{% for parking in user.parkings %}
<h2>Parking</h2>
{{ parking.libelle }}
<h2>voitures</h2>
<table id="file_export" class="table table-striped table-bordered">
<thead></thead>
<tbody>
{% if parking.voitures|length > 0 %}
{% for voitures in parking.voitures %}
<tr>
<td>
{{ voitures.matricule }}
</td>
<td class="center">
<span class="timer" data-expires="{{ voitures.getExpiresAt() }}"></span>
</td>
</tr>
{% endfor %}
{% else %}
<tr>
<td colspan="6">no records found</td>
</tr>
{% endif %}
</tbody>
</table>
{% endfor %}
<script>
var timers = document.querySelectorAll('.timer')
function updateTimers () {
var rightNow = Math.floor(Date.now()/1000) // in seconds
timers.forEach(function (timer) {
var expires = parseInt(timer.dataset.expires) // in seconds
if (rightNow > expires) {
// Time expired
timer.innerText = 'Expired'
} else {
var seconds = expires - rightNow
var minutes = Math.floor(seconds/60)
var hours = Math.floor(minutes/60)
var days = Math.floor(hours/24)
seconds = ('0' + String(seconds%60)).slice(-2)
minutes = ('0' + String(minutes%60)).slice(-2)
hours = ('0' + String(hours%24)).slice(-2)
timer.innerText = days + 'd ' + hours + 'h ' + minutes + 'm ' + seconds + 's'
}
})
setTimeout(function () {
updateTimers()
}, 100)
}
updateTimers()
</script>
{% endblock %}
筆記
如果要通過ajax添加更多計時器(在頁面加載后),則應(yīng)放置以下行:
var timers = document.querySelectorAll('.timer')
在功能塊內(nèi)部,可以在每次調(diào)用時搜索新的計時器。

TA貢獻1827條經(jīng)驗 獲得超9個贊
有重復(fù)的ID(“ test”,“ demo”),每個文件一個。
id全局屬性定義一個唯一標識符(ID),該標識符在整個文檔中必須是唯一的。其目的是在鏈接(使用片段標識符),腳本或樣式(使用CSS)時標識元素。
這document.getElementById("demo")
將返回一個結(jié)果,可能是DOM中的第一個結(jié)果。(我懷疑這也是對的,var test = $('#test').data("isTest");
但我不太熟練使用jQuery)。
也許您可以通過“名稱”屬性進行選擇,然后將代碼更改為具有一個<script>
可迭代所需節(jié)點的元素。
- 2 回答
- 0 關(guān)注
- 210 瀏覽
添加回答
舉報