rails coffeescrip使用setTimeout

rails5以后默认不集成jquery了,需要使用

yarn install jquery

安装,再使用

//= require jquery

加入到js

$(document).ready ->
  # 左侧菜单
  $('.ty-menu>li').each ->
    $(this).click ->
      console.log($(this).find('.ty-submenu'))
      if $(this).find('.ty-submenu')?
        # 其他的节点全部关闭
        $(this).siblings().find('.ty-submenu').slideUp()
        # 打开当前节点
        $(this).find('.ty-submenu').slideDown()

  # notice 消失
  if $('.ty-tip').length > 0
    setTimeout (-> $('.ty-tip').remove()), 3000 

好吧,经测试,ready只工作一次,官网是这样解释的:

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 upon 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!"

修改成下面的就可以了。

turbolinks事件

Turbolinks emits events that allow you to track the navigation lifecycle and respond to page loading. Except where noted, Turbolinks fires events on the document object.

  • turbolinks:click fires when you click a Turbolinks-enabled link. The clicked element is the event target. Access the requested location with event.data.url. Cancel this event to let the click fall through to the browser as normal navigation.

  • turbolinks:before-visit fires before visiting a location, except when navigating by history. Access the requested location with event.data.url. Cancel this event to prevent navigation.

  • turbolinks:visit fires immediately after a visit starts.

  • turbolinks:request-start fires before Turbolinks issues a network request to fetch the page. Access the XMLHttpRequest object with event.data.xhr.

  • turbolinks:request-end fires after the network request completes. Access the XMLHttpRequest object with event.data.xhr.

  • turbolinks:before-cache fires before Turbolinks saves the current page to cache.

  • turbolinks:before-render fires before rendering the page. Access the new <body> element with event.data.newBody.

  • turbolinks:render fires after Turbolinks renders the page. This event fires twice during an application visit to a cached location: once after rendering the cached version, and again after rendering the fresh version.

  • turbolinks:load fires once after the initial page load, and again after every Turbolinks visit. Access visit timing metrics with the event.data.timing object.

猜你喜欢

转载自blog.csdn.net/tang05709/article/details/86773174