试图在Jade中使用Inline JS变量

时间:2017-09-19 02:18:08

标签: javascript pug

我正在尝试使用变量count来跟踪标签h1中的页面刷新,但实际值没有被使用.H1呈现从快速服务器接收的一些数据。所以我访问索引处的数据是重载计数。

script.
  var state = history.state || {};
  var reloadCount = state.reloadCount || 0;
  if (performance.navigation.type === 1) { // Reload
    state.reloadCount = ++reloadCount;
    history.replaceState(state, null, document.URL);
  } else if (reloadCount) {
    delete state.reloadCount;
    reloadCount = 0;
    history.replaceState(state, null, document.URL);
  }
  if (reloadCount >= 2) {
    // Now, do whatever you want...
    console.log("Hello");
    //alert('The page was reloaded more than twice!');
  }
body
 h1 #{data[reloadCount].text}

1 个答案:

答案 0 :(得分:0)

问题在于你在这里混合了两个不同的东西:客户端JS(代码片段开头的脚本标签)和服务器端JS(在Pug中,在{{1中评估)声明)。 h1标记的内容在编译时评估,因此在服务器上,不知道h1的值。与reloadCount标记中的内容没有任何交互,因为它只是作为纯文本复制到Pug的输出HTML中。如果要在客户端(在浏览器中)动态更新某些内容,则需要使用客户端JS来设置该script.元素的值。