rails4 onclick事件不响应

rails4 新增了turbolinks插件,可以在项目的gemfile中看到  
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'

项目的manifest文件(一般是application.js)中

//= require turbolinks

这个gem官方文档里有这么一句话

With Turbolinks pages will change without a full reload, so you can't rely on DOMContentLoaded or jQuery.ready() to trigger your code. Instead Turbolinks fires events on document to provide hooks into the lifecycle of the page.


所以更新页面要用到它自定的事件,才能响应
  • page:before-change a Turbolinks-enabled link has been clicked (see below for more details)
  • page:fetch starting to fetch a new target page
  • page:receive the page has been fetched from the server, but not yet parsed
  • page:change the page has been parsed and changed to the new version and on DOMContentLoaded
  • page:update is triggered whenever page:change is PLUS on jQuery's ajaxSucess, if jQuery is available (otherwise you can manually trigger it when calling XMLHttpRequest in your own code)
  • page:load is fired at the end of the loading process.
当然也可以不用这个插件,方法是,把gemfile中的gem turbolinks注释掉,还有就是把去掉manifest文件中的
//= require turbolinks
就可以和往常一样使用了。
不过在有这个插件的情况下,也可以在元素里加上属性:data-no-turbolink,这样的话这个元素就不会用到该插件了,正常使用。

例如页面这样一个link
<a href="#" data-background-color = "#990000" data-no-turbolink >Paint it red</a>
对应的js.coffee这样写
paintIt = (element, backgroundColor, textColor) ->
  element.style.backgroundColor = backgroundColor
  if textColor?
    element.style.color = textColor
$ ->
  $("a[data-background-color]").click ->
    backgroundColor = $(this).data("background-color")
    textColor = $(this).data("text-color")
    paintIt(this, backgroundColor, textColor)
点击该link,会使自身背景变为深红色,
当去掉 data-no-turbolink 这个属性时,点击该link是没有反应的。

我也尝试了用turbolinks的事件来响应该点击事件,我这样做link
<a href="#" data-background-color = "#990000">Paint it red</a>
对应的js.coffee这样写
paintIt = (element, backgroundColor, textColor) ->
  element.style.backgroundColor = backgroundColor
  if textColor?
    element.style.color = textColor
$ .on "page:change",->
  $("a[data-background-color]").click ->
    backgroundColor = $(this).data("background-color")
    textColor = $(this).data("text-color")
    paintIt(this, backgroundColor, textColor)
虽然我用了page:change,但是效果却不是我想要的,点击link后,会变成深红色,不过马上又变回去了,还是对这个理解不深,不会使用的原因。
刚把利马斯!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值