Ruby-on-rails 如何添加 onchange 事件以在 Rails 中选择标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/979400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add an onchange event to select tag in rails
提问by Nave
How do I add an onchange event here?
如何在此处添加 onchange 事件?
Framework: rails
Database: MySQL
框架:rails
数据库:MySQL
I am populating the options from the database and that made me use options_from_collection_for_select
我正在从数据库中填充选项,这让我使用 options_from_collection_for_select
select_tag(:variable,options_from_collection_for_select(:all, :id, :name))
回答by Daniel Vandersluis
select_tagtakes an optionshash as its final parameter, in which you can add any HTML attributes for the select. So to add an onchangeattribute:
select_tag将options散列作为其最终参数,您可以在其中为选择添加任何 HTML 属性。所以要添加一个onchange属性:
select_tag :variable, options_from_collection_for_select(:all, :id, :name), :onchange => 'your_onchange_handler()'
回答by marsjo
try something like:
尝试类似:
:onchange => remote_function(:url => {:controller => 'controller', :action => 'action'})
回答by AmitF
For a select_tag, just add:
对于 select_tag,只需添加:
{:onchange => "myHandler();" }
Also, if onchange doesn't work you might want to try onChangewith a capital C.
此外,如果 onchange 不起作用,您可能想尝试onChange使用大写 C。
Finally, make sure NOT TO CONFUSE a select_tag with a form select.
最后,请确保不要将 select_tag 与表单选择混淆。
See my answer to a similar question, only regarding a form select and not a select_tag
请参阅我对类似问题的回答,仅关于表单选择而不是 select_tag
回答by jmjm
You may want to add an onchangeattribute inline:
您可能希望onchange内联添加属性:
select_tag(:variable,options_from_collection_for_select(:all, :id, :name)), {:onchange => "(function(e){ e.target.value }).apply(this,arguments)"}
For my case, I'm not sure where to put the named functions, or sometimes I find it tedious to create a function just to create a simple tag. So people tend to write an inline function.
就我而言,我不确定将命名函数放在哪里,或者有时我发现创建一个函数只是为了创建一个简单的标签很乏味。所以人们倾向于写一个内联函数。
but a simple line like {onchange: "e.target.value"}won't work, because there are no variables (e.g. event) defined.
但是像这样的简单行{onchange: "e.target.value"}不起作用,因为没有event定义变量(例如)。
Solution would be a self executing function that accepts arguments
解决方案是一个接受参数的自执行函数

