0

我在 application.js 文件中创建了一个 javascript 函数用于测试目的,但是当我在视图文件中内联使用该函数时,我无法访问它。

应用程序/资产/application.js:

//= require jquery
//= require jquery_ujs
//= require_tree .

$(document).ready(function() {
  function test() {
    alert('test');
  }
}

视图/布局/application.html.haml

:javascript
  test(); // gives me a Uncaught ReferenceError: test is not defined error
4

1 回答 1

0
$(document).ready(function() {
  test = function() {
    console.log("foo");
  }
});


// wait for document ready
$(document).ready(function() {
  test();
});

$(document).ready(function() {
  window.test();
});

这也会失败

$(document).ready(function() {
  var test = function() {
    console.log("foo");
  }
});

这也应该提供一些很好的阅读var functionName = function() {} vs function functionName() {}

于 2013-02-12T01:27:53.110 回答