【问题标题】:Coffeescript not working in modal window in rails with bootstrapCoffeescript 在带有引导程序的 Rails 的模态窗口中不起作用
【发布时间】:2015-05-29 13:57:45
【问题描述】:

我有 rails 控制器“contacts_controller.rb”,然后我在 contact.coffee 中有咖啡脚本代码。

我有索引视图,其中有引导模式窗口,我正在加载 new.html.erb

<div id="contact-modal" class="modal fade">
  <div class="modal-dialog">
    <div id="inner-contact-modal" class="modal-content"></div>
  </div>
</div>

我有一个简单的警报,可以在单击标题时执行,例如下面的代码将与 index.html.erb 一起使用

$ -> 
  $("#contacts-title").click ->
    alert "contacts-title is clicked"

但是无论我尝试在模式窗口中运行什么咖啡脚本代码,它都不起作用。

我是否必须为 _new.html.erb 视图创建单独的 .coffee 文件,或者我必须在 index.html.erb 中加载我的模态窗口后做一些事情,以便 .coffee 文件可以在模态窗口中看到选择器?

【问题讨论】:

  • 模态中的内容是通过 AJAX 交互加载的,还是在页面加载时加载?无论如何,您可能希望将 $(...).click 调用更改为 $(document).on('click', '...', ....
  • modal 加载按钮点击如下
  • 例如 $(".btn").click -> alert "blla blla blla" 在我点击 index.html.erb 中的按钮时有效,但在我点击新按钮时无效。我在 index.html.erb 中作为模态加载的 html.erb

标签: ruby-on-rails ruby-on-rails-4 coffeescript bootstrap-modal


【解决方案1】:

试试这个

$("body").on "click", "#contacts-title", ()->

正如 Santiago 在评论中提到的,您需要在使用 turbolinks 时在 js 文件中执行此操作,

ready = ()->
  $("body").on "click", "#contacts-title", ()->
    alert "contacts-title is clicked"
$(document).on 'page:load ready', ready

【讨论】:

  • 我收到错误:SyntaxError: [stdin]:27:40: unexpected ->
  • 你在哪里使用 erb 中的咖啡脚本代码?
  • 我的 coffescript 代码在 app/assets/javascripts/contact.coffee 中,当我加载 contacts/index.html.erb 但加载 new.html.erb 后它工作正常(在模态index.html.erb 中的窗口)代码在那里不起作用
  • 我相信在rails中保存coffeescript的正确方法是contact.js.coffee,你可能应该在DOM加载后绑定点击事件可能像这样$(document).on 'page:load ready', -&gt;
  • 是的,它现在正在工作,非常感谢你们帮助我:)
猜你喜欢
  • 1970-01-01
  • 2013-03-25
  • 2015-07-17
  • 1970-01-01
  • 1970-01-01
  • 2019-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多