在选择框的 onchange 期间调用 JavaScript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11543796/
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
Calling a JavaScript function during onchange of a select box
提问by coyotepoint
In my view, I have the following:
在我看来,我有以下几点:
<%= select("event", :event_id, events_ids_titles_hash, { :include_blank => true, :onchange => "alert_me_test()" }) %>
alert_me_test() is:
alert_me_test() 是:
<script type="text/javascript">
function alert_me_test()
{
alert ("this is a test")
}
</script>
The dropdown is appearing fine, but when I select from it, nothing happens. I'm expecting an alert box with "this is a test" in it.
下拉菜单看起来不错,但是当我从中选择时,什么也没有发生。我期待一个带有“这是一个测试”的警报框。
The Edit case:
编辑案例:
When I'm doing an edit, I have the following code:
当我进行编辑时,我有以下代码:
<% if @panel.event_id %>
<%= select("panel", :event_id, events_ids_titles_hash, {:selected => @panel.event_id}, { :include_blank => true}) %>
My IDE (RubyMine) does not want to accept the "onchange" as an additional argument, and putting it inside one of the :selected or :include_blank argument hashes does not produce an error, but it does not work either
我的 IDE (RubyMine) 不想接受“onchange”作为附加参数,并将其放入 :selected 或 :include_blank 参数哈希之一中不会产生错误,但它也不起作用
What ended up working for both new and edit:
什么最终对 new 和 edit 都有效:
<% if @panel.event_id %>
<%= 'Event is ' + events_ids_titles_hash.key(@panel.event_id) %>
<%= select("panel", :event_id, events_ids_titles_hash, {:selected => @panel.event_id}, { :include_blank => true, :onchange => "alert_me_test()"}) %>
<% else %>
<%= 'Select Event from list' %>
<%= select("event", :event_id, events_ids_titles_hash, { :include_blank => true }, { :onchange => "alert_me_test()" }) %>
<% end %>
回答by AdamCooper86
<%= select("event", :event_id, events_ids_titles_hash, { :include_blank => true, :onchange => "alert_me_test()" }) %>
Worked for me, but I must say that you are fighting against the current with this one. Rails follows UJS, which means your even handlers should be separate from your HTML. In this case the select would be the same minus the onclick and then the script would be
对我来说有效,但我必须说,您正在与此作斗争。Rails 遵循 UJS,这意味着您的偶数处理程序应该与您的 HTML 分开。在这种情况下,选择将是相同的减去 onclick,然后脚本将是
<script type="text/javascript">
$('select').change(alert_me_test);
function alert_me_test(){
...
}
</script>
You don't have to do things this way, but it makes it clearer when looking at a script where your event calls are coming from.
您不必以这种方式做事,但在查看您的事件调用来自的脚本时,它会更加清晰。
回答by Matthew Manela
I believe you need to set the :onchange
as an HtmlOption, which is a 4th parameter:
我相信您需要将其设置:onchange
为 HtmlOption,这是第四个参数:
<%= select("event", :event_id, events_ids_titles_hash, { :include_blank => true}, {:onchange => "alert_me_test()" }) %>