在Rails中调用javascript函数onclick [英] Call javascript function onclick in Rails
问题描述
我的一个观点中有以下代码:
I have the following code in one of my views:
<button type="button" onclick="analyze();">Analyze</button>
并且,相应控制器的 .js.coffee 文件包含
And, the .js.coffee file for the corresponding controller contains
analyze = ->
$.ajax
type: "GET"
url: "http://localhost:3000/api/logs"
success: (data) ->
Analytics.doAnalysis data
return;
return;
但是,当我点击按钮时,我在控制台中收到错误未捕获的ReferenceError:分析未定义。我认为我的onclick没有正确定义。建议的方法是什么?
But, when I click the button, I get an error in console saying Uncaught ReferenceError: analyze is not defined. I think my onclick is not correctly defined. What is the recommended way of doing this?
推荐答案
我是网络开发的新手
I am new to web development
由于您是新手,请告诉我如何改进您的代码:
Since you're new, let me give you some ideas on how to improve your code:
Rails约定适用于不引人注目的javascript功能。这意味着您可以将事件
分配给页面上的元素,而无需直接引用这些元素(不要使用内联 onclick
etc )
Rails convention is geared towards "unobtrusive" javascript functionality. This means you can assign events
to elements on your page without having to reference those elements directly (don't use inline onclick
etc)
这与CSS的描述最相似 - 使用内联
CSS是非常费力的&被视为不良做法(它不是 DRY
)。一个更好的方法是有一个中央样式表,然后你可以使用它来设置页面上的元素样式。
This is best described in the same way as CSS - using inline
CSS is ridiculously laborious & seen as bad practice (it's not DRY
). A much better way is to have a central stylesheet, which you can then use to style elements on the page.
不引人注目的Javascript以相同的方式工作 - 将所有内容保存在文件中你在运行时调用:
Unobtrusive Javascript works in the same way - keep everything in files you call at runtime:
#app/assets/javascripts/application.js
$(".element").on("click", function(){
...
});
这一点的重要性无法说明 - 拥有不引人注目的JS是最好的编程模式之一应用;它不仅可以破坏您的代码,还可以确保未来的开发能够保持模块化(黄金标准)正在开发中)
The importance of this cannot be stated enough - having unobtrusive JS is one of the best programming patterns you can apply; it not only DRIES up your code, but also ensures future development can be kept modular (a gold standard in development)
Ajax
由于你使用的是ajax,你可能希望使用 Rails UJS Ajax功能,这基本上意味着:
Since you're using ajax, you may wish to use the Rails UJS Ajax functionality, which basically means this:
<%= button_to "Analyze", analytics_api_path, id: "analyze", remote: true %>
remote:true
这个选项调用 Rails UJS驱动程序的 ajax
功能 - 基本上设置ajax调用,而无需编写任何代码。需要注意的是,您需要处理自己的 ajax:success
进程,并且需要将元素指向正确的 href
The remote: true
option of this calls the Rails UJS driver's ajax
functionality - basically setting up an ajax call without you having to write any code. The caveats of this are that you need to handle your own ajax:success
process, and you'll need to point the element to the correct href
我会这样做:
#app/assets/javascripts/application.js.coffee
$("#analyze").on "ajax:success", (data, status, xhr) ->
Analytics.doAnalysis data
这篇关于在Rails中调用javascript函数onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!