新手问题 Rails 页面跳转 jQuery 不工作

chengkai1853 · September 21, 2016 · Last by chengkai1853 replied at September 26, 2016 · 2857 hits

这个是导航栏的动效代码。点击 h2 标题的跳到新页面的时候,下面 js 的代码就失效了,导航栏不会有效果。如果我打开页面的调试工具,在控制台手动执行一遍$('#mainNav').affix的代码,导航栏效果就可用了。请问这是什么问题导致的啊?求教。 html 代码如下:

<div class="col-lg-12 text-center">
     <h2><%= link_to :Bike , bikes_url , rel:"external" %></h2>
     <hr class="star-primary">
</div>

Jquery 的代码如下,并且在 application.js 中 require 了它:

$(function() {
    "use strict"; // Start of use strict

    // Offset for Main Navigation
    $('#mainNav').affix({
        offset: {
            top: 100
        }
    })
})

打个断点调试一下,慢慢排查原因

已经在网上搜到原因了是因为 Turbolinks 具体链接JQuery in Rails is failing after linking from another page, works on page load

这个答案里面有一个有问题的地方,官网如下:

When writing CoffeeScript, you'll often want to do some sort of processing upon page load. With jQuery, you'd write something like this:
(document).ready ->
  alert "page has loaded!"

However, because Turbolinks overrides the normal page loading process, the event that this relies on will not be fired. If you have code that looks like this, you must change your code to do this instead:

$(document).on "turbolinks:load", ->
  alert "page has loaded!"

For more details, including other events you can bind to, check out the Turbolinks README.

js 放在 body 结束标签之前

事件触发的问题。 要不你把 turbolink dsiable, 要不就看看 turbolink 的文档,在 rails 下使用不能直接使用 jQuery 的某些事件。

@leiz_me 谢谢了,问题已经解决了!

You need to Sign in before reply, if you don't have an account, please Sign up first.