我一直在寻找,但找不到任何可以帮助我的东西。
我有一个文件countdown.js app / assets / javascript / countdown.js
// Total seconds to wait
var seconds = 11;
function countdown() {
seconds = seconds - 1;
if (seconds < 0) {
// Chnage your redirection link here
seconds = 11;
window.setTimeout("countdown()", 1000);
} else {
// Update remaining seconds
document.getElementById("countdown").innerHTML = seconds;
// Count down using javascript
window.setTimeout("countdown()", 1000);
}
}
// Run countdown function
countdown();
我想在index.html.erb文件中调用此函数。我该怎么办?
答案 0 :(得分:0)
你的js功能不好:
countdown
setInterval
而不是setTimeout
(source here in the "Definition and Usage" section)所以你可以做更多这样的事情:
//assets/javascript/countdown.js
function countdown() {
var seconds = 11
setInterval(function() {
if (seconds < 1) {
seconds = 11
}
seconds -= 1
document.getElementById("countdown").innerHTML = seconds + " seconds"
}, 1000);
}
window.onload = function() {
countdown();
};
确保您的资产/ javascript / application.js中的js文件是必需的:
//= require countdown
// OR
//= require_tree .
并且您的application.js在您的布局中链接:
#layouts/application.html.erb
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
现在,您可以使用id="countdown"