【问题标题】:CoffeeScript code only works after press home menuCoffeeScript 代码仅在按下主菜单后才有效
【发布时间】:2016-08-11 07:05:29
【问题描述】:

我正在使用 Rails 5。我有一个带有索引操作的 home_controllerroot 'home#index'。 index.html.erb上有一个按钮,我想按下这个按钮调用一些js代码(弹出窗口)。

但是我的咖啡脚本代码只有在我按下 Home 菜单后才被调用。所以我想知道/home#index 有什么不同吗?感谢您的帮助。

application.html.erb

<nav>
<li><%= link_to "Home", "/"%></li>
</nav>

index.html.erb

<button id="myBtn">Open Modal</button>
<div id="myModal" class="modal">
  <div class="modal-content">
    <span class="close">×</span>
    <p>Some text in the Modal..</p>
  </div>
</div>
<%= render :partial => 'stories/stories' %>

home.coffee

modal = document.getElementById('myModal');
btn = document.getElementById("myBtn");
span = document.getElementsByClassName("close")[0];
btn.onclick = ->
    modal.style.display = "block"
span.onclick = ->
    modal.style.display = "none"
window.onclick = (event) ->
    modal.style.display = "none" if event.target == modal

【问题讨论】:

    标签: ruby-on-rails coffeescript


    【解决方案1】:

    终于我明白了:把js代码放在定义的元素之后,这意味着DOM准备好回调,这里是JQuery DOM准备好在CoffeeScript中

    $ ->
        console.log("DOM is ready")
    

    【讨论】:

      猜你喜欢
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多