【问题标题】:jquery not running with rails in external js filejquery没有在外部js文件中使用rails运行
【发布时间】:2014-08-16 10:38:09
【问题描述】:

我正在使用 rails 并尝试调用外部 js 文件中存在的 jquery 代码,其路径我已在我的 html 文件中正确指定。当我将 jquery 代码直接包含在 html 文件中时,它正在正确执行。 我的 test.js

$(function(){

alert("yes");
});

和 index.html.erb :

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="/assets/javascripts/views/test.js"></script>

</head>

jquery 在包含在 html 中时执行

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){

alert("yes");
});
</script>
</head>

test.js 路径是正确的,因为其他 javascript 函数是从同一个文件而不是 jquery 代码中调用的

【问题讨论】:

  • 尝试将此文件包含在您的 application.js 中。

标签: javascript jquery html ruby-on-rails


【解决方案1】:

为什么你在 index.html.erb 文件中有 head 标签。它已经包含在 layout/application.html.erb 文件中。这样,您将包含 jquery 文件两次。如果您在任何 html 中包含两个版本的 jquery,它们总是会产生问题。

在我的建议中,您需要从索引文件中完全删除您的 head 标签。以及您想要包含的任何 js 文件,将其包含在您的 application.js 文件中。对于当前场景,您可以像下面那样做。

//= require views/test

【讨论】:

  • 这是导致问题的原因之一。非常感谢。
【解决方案2】:

@user3946910

像这样试试。

在您的 index.html 中

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="/assets/javascripts/views/test.js"></script>

</head>

然后在你的 test.js 文件中添加这个。

$(document).ready(function(){
alert("yes");
});

像这样只需在 html 本身中导入所有插件,并创建新的 .js 页面来编写您自己的脚本。

我希望它会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 2011-02-04
    • 2011-10-18
    相关资源
    最近更新 更多