【问题标题】:How can I access the DOM elements in PUG如何访问 PUG 中的 DOM 元素
【发布时间】:2020-04-08 17:33:16
【问题描述】:

我有一个从 Express 呈现的索引页面,并且有一个名为“data”的变量由 express 传递。 我想使用 mdbootstrap 和 express 传递的数据对象在模板中绘制图表。

我想做这样的事情:

canvas#lineChart

- function plot(data){
-   var context = document.getElementById("lineChart").getContext("2d");
-   var myChart = new Chart(context, data);
- }

- plot(data)

但它表明

无法获取未定义的属性“getElementById”

我该怎么办?

【问题讨论】:

  • 节点 js 或网络浏览器 html ??
  • 当 Pug 编译和运行任何代码块 javascript 时,DOM 不存在。如果您希望 javascript 在存在 DOM 的浏览器中运行,请将其放在 <script> 标记中。
  • 不是真的,但我会尝试一下。谢谢

标签: javascript node.js express pug


【解决方案1】:

你不能在 nodejs 中访问 DOM。由于它没有浏览器 ENV。您可以使用puppeteer 在 chrom 浏览器上加载 html。

如果您只是在 nodejs 中使用模板字符串。使用像cheerio 这样的模块。在节点 js 中处理类似 DOM 的结构。

const cheerio = require('cheerio')
const $ = cheerio.load('<h2 class="title">Hello world</h2>')

$('h2.title').text('Hello there!')
$('h2').addClass('welcome')

$.html()
//=> <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>

【讨论】:

  • 感谢您的回复,但我认为您没有收到我的问题。我知道在编译时无法访问 DOM,但这不是我需要的解决方案。
猜你喜欢
  • 2018-11-02
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 2015-05-08
  • 1970-01-01
  • 2013-10-26
  • 2017-03-03
相关资源
最近更新 更多