[英]How to move script from view to application.js in rails
Doing some research this is the code that worked for me but it is in the view and I would like to move to the application.js so I can use in different forms. 做一些研究,这是对我有用的代码,但是它在视图中,因此我想移至application.js,以便以不同的形式使用。
The other thing is that I have two scripts doing the same thing. 另一件事是我有两个脚本执行相同的操作。 One is for when I click on the checkbox and the other is to check if it is already checked when loading the page.
一种是当我单击复选框时,另一种是在加载页面时检查是否已选中。 Can I merge them so I don't have to repeat the code?
我可以合并它们,这样就不必重复代码了吗?
<script type="text/javascript">
function hideAddress()
{
if($('#same').is(":checked"))
$("#mailing-address").hide();
else
$("#mailing-address").show();
}
</script>
<script type="text/javascript">
$( document ).ready(function hideAddress() {
{
if ($('#same').is(":checked"))
$("#mailing-address").hide();
else
$("#mailing-address").show();
}
});
</script>
Edit 编辑
I tried moving to the application.js without the script tags, but now the .ready function doesn't work unless I reload the page. 我尝试移动到没有脚本标签的application.js,但是现在除非重新加载页面,.ready函数才起作用。
$( document ).ready(hideAddress);
function hideAddress()
{
if($('#same').is(":checked"))
$("#mailing-address").hide();
else
$("#mailing-address").show();
}
So it looks like turbolinks makes document ready not work properly, so instead of (document).ready
I had to do $(document).on('turbolinks:load'
. 所以看起来turbolinks使文档准备工作无法正常工作,所以代替
(document).ready
我不得不做$(document).on('turbolinks:load'
。
So i ended up setting this code on my application.js 所以我最终在我的application.js上设置了这段代码
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
$(document).on('turbolinks:load', hideAddress );
function hideAddress()
{
if($('#same').is(":checked"))
$("#mailing-address").hide();
else
$("#mailing-address").show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.