繁体   English   中英

用ejs的客户端javascript文件表达

[英]Express with ejs's client side javascript file

最近我正在尝试使用 express 和 ejs 创建一个网站,但我发现我不能只将一个 javascript 文件用于我的所有 ejs(视图)文件,因为当我以 DOM 元素为目标时,如果其他视图页面没有没有那个 DOM 元素我会在我的控制台中得到一个错误。

示例:(因此,如果正在访问索引页面,我很好,但是当我在 about 页面上时出现错误,因为带有 class 的元素在 about 页面上不存在)

索引.ejs

<div class="main-container">
    <h1 class="home-heading">Home page</h1>
    <p>some random text</p>
</div>

关于.ejs

<div class="main-container">
    <h1 class="about-heading">About page</h1>
    <p>some random text</p>
</div>

脚本.js

const homeHeading = document.querySelector('.home-heading');
homeHeading.style.backgroundColor = 'red'; 

所以我的问题是链接客户端 javascript 文件的最佳方法是什么? 我能想到的唯一方法是创建多个 js 文件并使其每个 ejs 页面都有自己的 js 文件,这是最佳实践吗? 或者有没有其他方法可以让我只使用一个js文件来让它工作?

现在这就是我想出的:

在视图页面(主页)上,我将创建一个值为 index 的变量并传递给页脚(部分)

索引.ejs

<%- include('../partials/header'); -%>
<h1>Hello world</h1>
<a href="/about" >about</a>
<% const currentPage = "index"; %>
<%- include('../partials/footer',{currentPage: currentPage}); -%>

页脚.ejs

  </div>
  <%- include('../partials/scriptFiles',{currentPage: currentPage}); -%>
 </body>
</html>

我将再次将变量向下传递给 scriptFiles.ejs(partial) 以检查我在哪个页面上以及 output 那个带有正确文件路径的 js 标记

脚本文件.ejs

<% let currentScriptFile = ''; %>

   <% if(currentPage === 'index'){ %>
      <% currentScriptFile = '<script src="./script.js"></script>'; %>
   <% }else if(currentPage === 'about') { ; %> 
      <% currentScriptFile = '<script src="./about.js"></script>'; %>
   <% } %>

<%- currentScriptFile %> //Output script tag with correct file path

因此,当我在主页上时,它将使用./script.js,而当我在关于页面上时,它将使用./about.js,将express与ejs一起使用是正确的方法吗? 如果不是最好的方法或正确的方法是什么。

谢谢

因此,如果我正在访问索引页面,我很好,但是当我在关于页面上时,我收到一个错误,因为该类的元素在关于页面上不存在

健壮地编写 JavaScript,以便它可以应对这种状态。

const duck = document.querySelector(".duck");
if (duck) {
    // The element exists and you can do stuff with it.
}

我真的在为这些而苦苦挣扎,你知道,我使用了很多 axios,并想为我的前端 ejs 做自定义脚本,但我无法让它们工作,我不认为这是最好的方法是按照答案中的建议进行操作,因为一旦在我的案例登录中请求了 ejs 模板,我什至没有答案,但是,我想现在就是这样,在本地。

暂无
暂无

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

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