简体   繁体   English

有没有在 Rails 视图中调用 javascript 函数?

[英]Is there anyway to call javascript function inside Rails view?

I am wondering if there's a way to call a javascript function:我想知道是否有办法调用 javascript 函数:

function get_url(link) {
  var url = window.location.href;
  var params = url.split('/')[3]
  return params == link ? 'active-menu' : ''
}

get_url('#about');

Inside rails views links like this:在 rails 中查看链接如下:

<li class="nav-item">
     <%= link_to "About", root_path(:anchor => 'about'), class: "nav-link #{javascript(get_url('#about'))}", :"data-id" => "about" %>
</li>

Notice this part:注意这部分:

class: "nav-link #{javascript(get_url('#about'))}"

Is there a way to do this?有没有办法做到这一点? If not, is there a better way to do this?如果没有,有没有更好的方法来做到这一点?

You can defer that function call to client-side scripts:您可以将该函数调用推迟到客户端脚本:

  1. add a class to these menu elements so that you can easily fetch all these, for example js-nav-link为这些菜单元素添加一个类,以便您可以轻松获取所有这些元素,例如js-nav-link
  2. in js on dom content loaded calculate and add necessary classes:在加载 dom 内容的 js 中计算并添加必要的类:
document.addEventListener('DOMContentLoaded', function(){
  let hash = window.location.hash;
  if(!!hash){
    let activeMenu = document.querySelector(`.js-nav-link[data-id="${hash}"]`);
    if(activeMenu){
      activeMenu.classList.add('active-menu');
    }
  }
});

Also you might want to look more deeply into utilising native anchors - give an id to an a -element ( link_to yields it), use window.location.hash to get # -part of url etc.此外,您可能想更深入地研究如何使用原生锚点 - 为a元素提供一个idlink_to产生它),使用window.location.hash获取# -part of url 等。

Trying to do this server side is a fools errand since the hash segment of a URL is not sent by browsers.尝试在服务器端执行此操作是愚蠢的差事,因为浏览器不会发送 URL 的哈希段。 But if I have understood you correctly and you just want to add a class to links that match the hash you can just do it with:但是,如果我对您的理解正确,并且您只想向与哈希匹配的链接添加一个类,您可以使用以下命令:

document.addEventListener("DOMContentLoaded", function(){
  if (window.location.hash) {
    document.querySelectorAll('a.nav-link[href="#%"]'.replace('%', window.location.hash))
            .forEach(function(link){
               link.classList.add('active');
            });
  }
});

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

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