我有一个简单的脚本来隐藏和显示某些按钮,但是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();
        }

    });
});

这是清单文件。
// 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

最佳答案

你的问题是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);

10-06 13:31
查看更多