![](/img/trans.png)
[英]How to call a Javascript Function which is nested inside a forEach loop
[英]How to call a javascript function inside a loop
如何像“onload”一样调用 javascript function?
我是说。 我正在尝试调用 CountDownTimer() function 但我不知道该怎么做。 有人能帮我吗?
附言。 javascript function 工作正常。
在我看来,我正在尝试这种方式:
@foreach (var item in Model.pedidosAberto)
{
<div class="col-lg-6 mb-4">
<a href="#" data-toggle="modal" data-id="@item.IdPedido" data-partial="_AbertoPartial"
data-modal="#Modal" class="card bg-success text-white text-decoration-none">
<div class="card-body">
<div class="float-right">
<div id="countdown_@item.IdPedido"></div>
<script type="text/javascript">
CountDownTimer('06/12/2021 4:45 PM', 'countdown_@item.IdPedido');
</script>
</div>
</div>
</a>
</div>
}
同样的观点,我有这个:
@section scripts{
<script type="text/javascript">
$(document).ready(function () {
//CountDownTimer('06/12/2021 4:45 PM', 'countdown');
function CountDownTimer(dt, id) {
var end = new Date(dt);
alert(end);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = 'EXPIRED!';
return;
}
//var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
//document.getElementById(id).innerHTML = days + 'days ';
document.getElementById(id).innerHTML = hours + ':';
document.getElementById(id).innerHTML += minutes + ':';
document.getElementById(id).innerHTML += seconds;
}
timer = setInterval(showRemaining, 1000);
}
});
</script>
您可以从现有脚本中获取倒计时元素,无需在 html 标记中嵌入无穷无尽的脚本。
首先将 class 添加到您的倒计时元素
<div id="countdown_@item.IdPedido" class="countdown"></div>
如果每个元素都有一个特定的日期字符串,您可以添加一个数据属性来保存该字符串,您可以在 go 运行 function 时检索该字符串。
<div id="countdown_@item.IdPedido" class="countdown" data-date="06/12/2021 4:45 PM"></div>
然后在现有文档中准备好 function,获取所有倒计时元素并使用来自该元素的数据为每个元素运行 function。
$(document).ready(function () {
$('.countdown').each(function() {
var dateString = $(this).attr('data-date');
var thisId = $(this).attr('id');
CountDownTimer(dateString, thisId);
}
// existing code....
}
您正在$(document).ready()
调用中的匿名 function中定义function CountDownTimer(....)
。 结果, CountDownTimer
function 仅在匿名 function 执行期间才知道,并且当匿名<div>
尝试在您的脚本中结束时,它不再存在。
要解决此问题,请从$(document).ready()
调用中取出CountDownTimer
- 或者如果其中只有这些,则考虑仅删除$(document).ready()
调用。
所以代替这个:
<script type="text/javascript">
$(document).ready(function () {
//CountDownTimer('06/12/2021 4:45 PM', 'countdown');
function CountDownTimer(dt, id) {
// ...
}
});
</script>
... 做这个:
<script type="text/javascript">
function CountDownTimer(dt, id) {
// ...
}
$(document).ready(function () {
//CountDownTimer('06/12/2021 4:45 PM', 'countdown');
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.