Javascript 带咖啡和jquery的Rails 5
我在rails中使用coffee脚本时遇到了一些问题,更重要的是原则和理解,而不仅仅是我的脚本 我有这样的咖啡剧本:Javascript 带咖啡和jquery的Rails 5,javascript,ruby-on-rails,coffeescript,Javascript,Ruby On Rails,Coffeescript,我在rails中使用coffee脚本时遇到了一些问题,更重要的是原则和理解,而不仅仅是我的脚本 我有这样的咖啡剧本: -> $('form').on 'click', '.add_fields', (event) -> alert('my test message') 它被编译成 (function() { // Place all the behaviors and hooks related to the matching controller here.
->
$('form').on 'click', '.add_fields', (event) ->
alert('my test message')
它被编译成
(function() {
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
// You can use CoffeeScript in this file: http://coffeescript.org/
$(function() {
return $('form').on('click', '.add_fields', function(event) {
return alert('my test message');
});
});
}).call(this);
我遇到的问题是,当我手动将这部分编译代码放入控制台时,事件从不触发,但我无法拥有最外层的函数。我是不是用错了,或者有人能给我解释一下调用(this)是如何工作的,这样我就可以在咖啡脚本中加入适当的结构
$(function() {
return $('form').on('click', '.add_fields', function(event) {
return alert('my test message');
});
});
谢谢。这是最后一个有效的咖啡脚本
$(document).on('turbolinks:load', ->
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('fields').replace(regexp, time))
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault())
您是否启用了涡轮链接?如果是这样,请将
$('form')
绑定包装在turbolinks:load
事件侦听器中。您是正确的,它已修复。仍然想知道TurboLink总体上是如何影响这一点的。但这项活动现在起作用了。回答如下检查Turbolinks文档,特别是关于该事件侦听器的部分。Turbolinks在后台执行一些操作,使您的网站触发不同的事件。为了提供其功能,您可以调整您的工作流以使用Turbolinks,或者在不需要时禁用它。在更改代码之前,请阅读de README以确定是否确实需要它。