我正在 Asp.net MVC 中的一个拍卖网站上工作,我正在尝试能够显示每件元素的拍卖还剩多少时间的计时器。我使用我的模型将项目列表传递到我的 cshtml 页面,然后像这样遍历它们:
我的启动计时器的 javascript 函数:
function countdown(time) {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = time - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="timeLeft"
document.getElementById("timeLeft").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
}, 1000);
然后是我模型的迭代器,用项目的结束日期调用 js 函数
@foreach (var item in Model)
{
//code here
countdown(@item.EndDate)
<text id="timeLeft"></text>
}
我的脚本被 <script src="~/Scripts/countdown.js" />
引用了
The problem I am having is how to call this js function with a c# razor variable. Doing something basic for one item like:
<body onload= "countdown('@item.EndDate')">
When I put my razor variable it greys out my function. How do I need to go about passing my variable into my js function?
EX: (with singular Model item)
最佳答案
试试这个语法:
@foreach (var item in Model)
{
//code here
countdown(`${@item.EndDate}`)
}
关于javascript - 将 Razor 变量传递给 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51198880/