问题描述
我正在尝试从 Coffeescript 文件调用一个 JavaScript 函数,用于我的 $(document).ready()
并且它永远不会被调用.
I'm trying to call a javascript function from a Coffeescript file, for my $(document).ready()
and it's never getting called.
我要调用的函数来自一个外部源,它包含在我的 html 头元素中,就在我的咖啡脚本文件的包含之前,如下所示:
The function I want to call comes from an external source that I have included in my html head element, just before the include of my coffeescript file, like this:
<script src="external.js"></script>
<%= javascript_include_tag params[:controller], 'data-turbolinks-track' => true %>
在我的咖啡脚本文件(称为 someControllerName.coffee)中,我这样做:
and in my coffeescript file (called someControllerName.coffee) I do this:
ready = ->
... call my method
$ -> ready
这是正确的方法吗?我可以在 Chrome 中看到我的脚本已编译为 javascript,我可以在检查器的网络"选项卡中看到它.
Is this the correct way? I can see in Chrome that my script is compile to javascript, and I can see it in the Network tab of the inspector.
我使用的是 Rails 4,这是我的 application.js
I'm using Rails 4, and this is my application.js
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require_tree .
如果我用 alert("...");
替换我的方法调用,它会起作用,如果我在 $(document).ready() 中使用 javascript 调用我的 javascript 方法
效果很好.
If I replace my method call by alert("...");
it works, and if I call my javascript method using javascript in $(document).ready()
it works fine.
这是我真正的 javascript 函数:
Here's my real javascript function:
var ready = function () {
$('pre code').each(function (i, e) {
hljs.highlightBlock(e)
});
};
$(document).ready(ready);
我解决了这个问题:
highlight = ->
$("pre code").each (i, e) ->
hljs.highlightBlock(e)
$(document).on 'ready page:load', ->
highlight()
推荐答案
这和你想的不一样:
$ -> ready
在 JavaScript 中是:
In JavaScript that is:
$(function() {
return ready;
});
您的问题是 ready
只是对函数的引用,它不像在 Ruby 中那样是函数调用.您必须说 ready()
才能调用该函数,函数调用括号仅在您使用参数调用函数时是可选的:fx
和 f(x)
相同,但 f
和 f()
不同.
Your problem is that just ready
is simply a reference to the function, it is not a function call like it would be in Ruby. You'd have to say ready()
to call the function, the function calling parentheses are only optional when you're calling a function with arguments: f x
and f(x)
are the same but f
and f()
are different.
我想你想说:
$ -> ready()
甚至:
$ ready # same as $(ready)
这篇关于我可以从咖啡脚本文件中调用 Javascript 函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!