Rails javascript 仅在重新加载后才有效 [英] Rails javascript only works after reload

查看:30
本文介绍了Rails javascript 仅在重新加载后才有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题正是标题所说的.javaScript 在资产管道中,即 assets/javascripts/myfile.js.coffee 在 application.js 我有:

The problem is exactly what the heading says. The javaScript is in the asset pipeline i.e assets/javascripts/myfile.js.coffee In the application.js I have:

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require jquery.ui.all
//= requier twitter/bootstrap
//= require jasny-bootstrap
//= require_tree .

这是咖啡脚本

$(document).ready ->
  $("#close").click ->
    $(this).parent().parent().slideUp("slow")




  $( "#datepicker" ).datepicker
    dateFormat : "yy-mm-dd"


  player_count = $("#player option").length


  $('#btn-add').click ->
    $('#users option:selected').each ->
      if player_count >= 8
        $('#select-reserve').append("<option      value='"+$(this).val()+"'>"+$(this).text()+"</option>")
        $(this).remove()    
      else
        $('#player').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>")
        $(this).remove()
        player_count++


  $('#btn-remove').click ->
    $('#player option:selected').each ->
      $('#users').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>")
      $(this).remove()
      player_count--


  $('#btn-remove-reserve').click ->
    $('#select-reserve option:selected').each ->
      $('#users').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>")
      $(this).remove()


  $("#submit").click ->
   $("select option").prop("selected", "selected")

我可以在浏览器的源代码中看到已经加载了 javaScript,但它只有在我重新加载页面后才能工作.

I can see in the source code on the browser that the javaScript has been loaded, but it only works after I reload the page.

推荐答案

这是一个 turbolinks 问题.感谢@zwippie 带领我走向正确的方向!解决方案是将我的咖啡脚本包装成这样:

This was a turbolinks problem. Thanks to @zwippie for leading me in the right direction! The solution was to wrap my coffeescript in this:

ready = ->
// functions

$(document).ready(ready)
$(document).on('page:load', ready)

这篇关于Rails javascript 仅在重新加载后才有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆