仅在 onclick 事件上执行 erb 函数 [英] execute erb function only on onclick event
问题描述
我正在尝试构建一个 ruby on rails 应用程序,单击按钮会调用特定的函数.我把这个函数放在一个辅助模块中,我用 onclick 事件调用这个函数.我的问题是,即使我没有单击按钮,ERB 代码似乎还是会运行.我通过用正常工作的警报替换对函数的调用来测试按钮,只有当我单击按钮时才会弹出,但似乎在 html 中混合 erb 使其自动运行.我还尝试通过添加一个由 onclick 事件调用的 javascript 函数来通过中间步骤,但它并没有解决我的问题,因为代码无论如何都在运行.
I am trying to build a ruby on rails app where a button click would call a specific function. i put the function in a helper module and I am calling the function with the onclick event. my issue is that it seems like teh ERB code is run anyway, even when I do not click the button. I tested the button by replacing the call to the function by an alert which works properly, only popping up when I click the button, but it seems like that mixing erb inside html makes it run automatically. I also tried to pass through an intermediary step by adding a javascript function called by the onclick event, but it does not solve my issue as the code is run anyway.
index.html.erb
<input type="button" name="test" value="Charger en masse" onclick="<%charger_photos%>">
module CartephotosHelper
def charger_photos
@test=Array.new
Dir['./public/images/*'].each do |file_name|
@test.push(file_name)
next if File.directory? file_name
end
end
end
通过javascript调用onclick事件之外的函数进行测试
test by using javascript to call the fucntion outside of the onclick event
index.html.erb
<script type="text/javascript">
function chargermasse(){
<%charger_photos%>
}
</script>
<input type="button" name="test" value="Charger en masse" onclick="chargermasse()">
推荐答案
erb
是 Embedded RuBy,运行在服务器端,javascript
运行在客户端(例如:浏览器).您正在尝试在客户端上运行 erb
,这是一个服务器端代码.它不起作用.
erb
is Embedded RuBy, which is run on the server and javascript
is run on the client (ex: browser). You are trying to run the erb
, which is a server side code, on the client. It doesn't work.
您需要做的是,在客户端,onClick
事件应该调用服务器,收集这些结果并用这些结果更新 dom
.
What you need to do is, on the client side, the onClick
event should call server, gather those results and update the dom
with those results.
有关详细信息,请参阅working_with_javascript_in_rails.
Refer to working_with_javascript_in_rails for more info.
这篇关于仅在 onclick 事件上执行 erb 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!