简体   繁体   English

将重点放在Rails Flash消息上

[英]placing focus on rails flash message

Here is a rails controller redirect statement. 这是一个Rails控制器重定向语句。

redirect_to "controller_action_path", error: err.to_s 

The statement generates the following HTML in the browser's page source. 该语句在浏览器的页面源中生成以下HTML。

<div class="alert alert-danger alert-error" role="alert">"Your alert here"</div>

Problem: How do you create focus around the flash response message that appears at the top of the page. 问题:如何围绕页面顶部显示的Flash响应消息创建焦点。 Attempted Solutions(s): 尝试的解决方案:

<% if flash[:error] %>
  <%= javascript_tag do %>
    $('.alert-danger').focus();
  <% end %>
<% end %>

This works if the HTML element has an id tag. 如果HTML元素具有id标记,则此方法有效。 Perhaps if the HTML element has a class too. 也许HTML元素也有一个类。 It seems as if static elements can receive the focus, but, since the flash error message is generated by the rails framework and is a dynamically generated element, either it has not rendered on the form at the time focus is attempted to be applied, or it cannot find the element in the page's HTML. 似乎静态元素可以接收焦点,但是,由于flash错误消息是由rails框架生成的并且是动态生成的元素,因此它在尝试应用焦点时尚未呈现在表单上,​​或者它无法在页面的HTML中找到该元素。 The later does not appear to be the situation since the debugger returns the HTML for $('.alert-danger').focus(); 由于调试器返回$('.alert-danger').focus();的HTML,因此似乎不是后者$('.alert-danger').focus();

Rails generates static html and sends it to the client, so anything Rails generates is rendered at the same time as all other HTML. Rails生成静态html并将其发送到客户端,因此Rails生成的任何内容都将与所有其他HTML同时呈现。

Try changing your controller code to redirect_to "controller_action_path", alert: err.to_s and change your condition wrapping the jQuery function to <%= if flash[:alert] %> . 尝试将您的控制器代码更改为redirect_to "controller_action_path", alert: err.to_s ,并将包装jQuery函数的条件更改为<%= if flash[:alert] %> :error is not a valid option for redirect_to http://api.rubyonrails.org/classes/ActionController/Redirecting.html :error不是redirect_to http://api.rubyonrails.org/classes/ActionController/Redirecting.html的有效选项

I also don't think the conditional on the jQuery is necessary. 我也不认为jQuery的条件是必要的。 If there's no error then there should be no visible tag with that error class anyway. 如果没有错误,那么该错误类也应该没有可见的标记。

Also $.focus() doesn't work on every element by default https://api.jquery.com/focus/ 同样, $.focus()默认情况下也不适用于每个元素https://api.jquery.com/focus/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM