开发者问题收集

以下链接后未添加 Javascript 事件监听器

2021-02-10
75

我正在使用按钮来控制可折叠的侧边栏菜单。在初始加载时,按钮工作正常。在跟踪链接并检查元素后,我可以知道未添加事件侦听器,并且按钮停止工作,直到我刷新页面。我是 Rails 新手,所以我不确定为什么会这样。任何帮助都非常感谢!

HTML:

<html>
  <head>
    <title>BugSmacker</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
  </head>

  <body>
    <div id="page-container">
      <div id="content-wrap">
        <div class="bg-dark py-3">
          <h1 class="nav-title pl-2"> <span class="bug-title" >Bug</span> Smacker</h1>
        </div>
        <div class="py-3 second-nav">
          <button id="navbtn" class="btn nav-btn btn-lg fs-2">&#9776;</button>
        </div>
        <div id="mySidebar" class="sidebar" data-open="false">
          <%= link_to 'Home', root_path %>
          <%= link_to 'Sign In', new_user_session_path %>
          <%= link_to 'Sign Up', new_user_registration_path %>
        </div>
        <div id="main" class="px-0 py-0">
          <%= yield %>
        </div>
      </div>
      <footer id="footer" class="bg-dark pt-3">
        <a href="#" class="footer-link mx-2">Home</a>
        <a href="#" class="footer-link mx-2">About</a>
        <a href="#" class="footer-link mx-2">Contact</a>
      </footer>
    </div>
  </body>
</html>

Javascript:

import Turbolinks from "turbolinks";
import * as ActiveStorage from "@rails/activestorage";
import "channels";

Rails.start();
Turbolinks.start();
ActiveStorage.start();
require("jquery");

document.addEventListener("DOMContentLoaded", () => {
  function openNav() {
    const sidebar = document.getElementById("mySidebar");
    sidebar.dataset.open = "true";
    sidebar.style.width = "250px";
    document.getElementById("main").style.marginLeft = "250px";
  }

  function closeNav() {
    const sidebar = document.getElementById("mySidebar");
    sidebar.dataset.open = "false";
    sidebar.style.width = "0";
    document.getElementById("main").style.marginLeft = "0";
  }

  function toggleNav() {
    const sidebar = document.getElementById("mySidebar");
    const isOpen = sidebar.dataset.open;
    if (isOpen === "true") {
      closeNav();
    } else {
      openNav();
    }
  }

  var openBtn = document.getElementById("navbtn");
  openBtn.addEventListener("click", toggleNav, false);
});
1个回答

进行以下更改。

# old
document.addEventListener("DOMContentLoaded", () => {

# new
document.addEventListener("turbolinks:load", () => {
sam
2021-02-10