简体   繁体   English

是否可以访问和修改从Pug中的Express传递的变量?

[英]Is it possible to access and modify a variable passed from Express in Pug?

I'm making a simple math game and wanted to pass an array of questions into Pug. 我正在做一个简单的数学游戏,想将一系列问题传递给帕格。 If the user gets a question correct, I want to update the score and display a new question. 如果用户正确回答了一个问题,我想更新分数并显示一个新问题。 However, I wasn't sure how I could access and update the website dynamically through Pug... 但是,我不确定如何通过Pug动态访问和更新网站...

Passing the values in Express: 在Express中传递值:

return res.render('play', { questions: questionArray, score: 0});

Pug file: 哈巴狗文件:

p#question #{questions[score].num1} #{questions[score].operation}  #{questions[score].num2} 
  p#score #{score}
  input#answer
  button.btn.btn-primary(onclick='checkAnswer(questions[score], score)') Enter

When I click the button to check the answer, I get the error "questions is not defined at HTMLButtonElement.onclick" in the console. 当我单击按钮检查答案时,在控制台中出现错误“在HTMLButtonElement.onclick上未定义问题”。 I checked around on how to use onclick in Pug but it didn't seem to work. 我检查了如何在Pug中使用onclick,但似乎没有用。 Some people suggested JSON.stringify, but it didn't seem to work. 有人建议使用JSON.stringify,但似乎没有用。

Thanks in advance! 提前致谢!

You can use, PUG String Interpolation , like here; 您可以像这里使用PUG String Interpolation

p#question #{questions[score].num1} #{questions[score].operation}  #{questions[score].num2} 
    p#score #{score}
    input#answer
    button.btn.btn-primary#check-button Enter

script(type="text/javascript").
    document.getElementById('check-button').addEventListener('click', function() {
        let score = !{score};
        let qScore = !{quesstions[score]}
        // put things in "checkAnswer" function here
    });

Hope this works! 希望这有效! :) :)

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

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