使用Java检查URL中的参数以更改按钮颜色

问题描述 投票:1回答:1

在我的Rails 6应用中,我想检查Url中的参数ID,并更改具有相同ID的按钮。例如:http://localhost:3000/en/search?category=9,应更改id =“ 9”

的按钮

我的按钮就像这样:

 <div class="tooltip-wrap">
  <%= link_to request.params.merge(category: "9"), class: "button is-rounded", id: "9" do %>
  <i class="fas fa-thermometer-full"></i><%= (t "service.title").truncate(17) %>
  <% end %>                                      
  </div>

Javascript函数

<script>
if (window.location.search.indexOf('category=' + "{n}") > -1){
$('#{n}').addClass('has-background-primary');
};
</script>

网址类似:

http://localhost:3000/en/search?category=9
javascript window.location
1个回答
0
投票

尝试这样操作

<div class="tooltip-wrap">
  <%= link_to request.params.merge(category: "9"), class: "button is-rounded #{'color-class' if params[:category] == '9'}", id: "9" do %>
    <i class="fas fa-thermometer-full"></i><%= (t "service.title").truncate(17) %>
  <% end %>                                      
</div>

更清洁,无需依靠JavaScript即可正确解析网址并找到参数。

似乎这样是最好的解决方案,除非他们在rails 6.1中添加class_names帮助器。看到这里:https://blog.bigbinary.com/2020/02/04/rails-6-1-introduces-class_names-helper.html

© www.soinside.com 2019 - 2024. All rights reserved.