javascript - 与 node.js 中的 res.render() 一起使用的 ejs 文件中的 "document is not defined "错误?

标签 javascript node.js express

我有这个 ejs 文件,将使用 node.js 中的 res.render() 作为响应发送

<!DOCTYPE html>
<html>
<head>  
  <title>pilcit</title>
</head>
<body>
<% var btn = document.getElementById('btn');%>
<% btn.style.background="blue"; %>
<div class="pt-5">
<div class="container-fluid">
    <h1  style="color:blue;" align=center>Pilcit</h2>
    <h4 style="color:#369bf4" align="center">The online clipboard</h4>

     <div>

         <textarea  class="form-control mt-5" name="content" rows="12">
            <%= result.content %>
         </textarea>
         <input type="text" value="sdfdsfsdfsd"  id="foo">
         <button id="btn" data-clipboard-target="#foo" copy clip </button>


    </div>  
    <!--<input type="submit" value="Create Clip">-->

</div>

但是线
`<% var btn = document.getElementById('btn');%>

给我这个错误

ReferenceError: /home/ubuntu/workspace/pilcit/views/show.ejs:34
32| </head>
33| <body>
 >> 34|     <% var btn = document.getElementById('btn');%>
35| <div class="pt-5">
36| 
37|     <div class="container-fluid">

document is not defined
at eval (eval at compile (/home/ubuntu/workspace/pilcit/node_modules/ejs/lib/ejs.js:618:12), <anonymous>:17:27)
at returnedFn (/home/ubuntu/workspace/pilcit/node_modules/ejs/lib/ejs.js:653:17)
at tryHandleCache (/home/ubuntu/workspace/pilcit/node_modules/ejs/lib/ejs.js:251:36)
at View.exports.renderFile [as engine] (/home/ubuntu/workspace/pilcit/node_modules/ejs/lib/ejs.js:482:10)
at View.render (/home/ubuntu/workspace/pilcit/node_modules/express/lib/view.js:135:8)
at tryRender (/home/ubuntu/workspace/pilcit/node_modules/express

我没有使用 <% var btn = document.getElementById('btn');%> 来更改 btn 的背景颜色,我想将它与剪贴板 js 一起使用。 我用那一行来检查嵌入式 javascript 是否正常工作。

最佳答案

您不能在 ejs 标签内使用 document,因为该代码是在服务器上执行的。相反,您应该添加一个脚本标记,该标记将在页面实际加载到浏览器中时立即运行。

<script> var btn = document.getElementById('btn'); </script>

关于javascript - 与 node.js 中的 res.render() 一起使用的 ejs 文件中的 "document is not defined "错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54025731/

相关文章:

node.js - 按日期时间字段获取最新的 MongoDB 记录

没有模板引擎的 Node.js

javascript - Nodejs 将我的图像从 View 上传到 Controller

node.js - 如何在同一台服务器上运行多个实例?

javascript - 需要 Node 中的单例实例

javascript - IE-11 : Object doesn't support property or method 'parseInt'

javascript - 在 Qt 中将 C++ 对象暴露给 Javascript

javascript - ExpressJS中如何在一段时间后从字典中删除对象

html - 使用 Hogan.js 进行部分处理

javascript - 如何使用 Ajax 提交表单并获取一些文本作为返回