CPr*_*ide 1 html javascript ruby jquery ruby-on-rails-4
我有一个简单的脚本来隐藏和显示某些按钮,但javascript不会运行,直到重新加载页面.如果用户点击该链接,我怎样才能让它运行?例如,在用户第一次链接到页面时,页面已经隐藏了某些div.
var array = [".section-1", ".section-2", ".section-3", ".section-4", ".section-5"];
var cnt = 0;
$(function() {
for(var i = 0; i < 5; i++) {
$(array[i]).hide();
}
$(array[cnt]).show();
$(".previous").hide();
$(".next").click(function () {
if(cnt < 4){
$(array[cnt]).hide();
cnt++;
$(array[cnt]).show();
}
if (cnt == 4) {
$(".next").hide();
}
if(cnt > 0) {
$(".previous").show();
}
});
$(".previous").click(function (){
if(cnt > 0) {
$(array[cnt]).hide();
cnt--;
$(array[cnt]).show();
}
if(cnt < 4){
$(".next").show();
}
if(cnt == 0){
$(".previous").hide();
}
});
});
Run Code Online (Sandbox Code Playgroud)
这是清单文件.
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require users
Run Code Online (Sandbox Code Playgroud)
你的问题是turbolinks
问题是Turbolinks阻止你的JS"正常"加载,因为它每次都通过ajax重新加载页面的主体(破坏你的JS,因为你的所有事件都不会被绑定)
这两个解决方案是编写JS以与Turbolinks一起使用,或使用jquery-turbolinks来实现更自然的解决方案
如果您想让当前代码与Turbolinks一起使用,您可以使用:
var ready = function(){
var array = [".section-1", ".section-2", ".section-3", ".section-4", ".section-5"];
var cnt = 0;
for(var i = 0; i < 5; i++) {
$(array[i]).hide();
}
$(array[cnt]).show();
$(".previous").hide();
$(".next").click(function () {
if(cnt < 4){
$(array[cnt]).hide();
cnt++;
$(array[cnt]).show();
}
if (cnt == 4) {
$(".next").hide();
}
if(cnt > 0) {
$(".previous").show();
}
});
$(".previous").click(function (){
if(cnt > 0) {
$(array[cnt]).hide();
cnt--;
$(array[cnt]).show();
}
if(cnt < 4){
$(".next").show();
}
if(cnt == 0){
$(".previous").hide();
}
});
});
$(document).on("page:load ready", ready);
Run Code Online (Sandbox Code Playgroud)