小弟這幾天在學web前後端,目前想實現一個英文選擇題考試,
主要問題是卡在如何讓app.js的result變數能傳到script.js,
讓我能用result的長度去for(i<result.length)?
我覺得我的code流程感覺很奇怪,但我不知道要怎麼讓整個流程變得更順暢
希望大大們能提供意見給小弟做修正,感謝。
const express = require("express")
const expressLayouts = require('express-ejs-layouts');
const fs = require("fs")
const app = express()
app.use(express.static('public'))
app.use('/css', express.static( __dirname+'public/css'))
app.use(expressLayouts)
app.set('layout', './layouts/main');
app.set('view engine', 'ejs');
var file = "test.json"
var result = JSON.parse(fs.readFileSync(file))
app.get("/", (req,res)=>{
res.render("index",{title: "English-testing",data:result})
})
var btn = document.getElementById("btn");
btn.addEventListener("click", () => {
showDiv();
});
function showDiv() {
for (var i = 0; i < 2; i++) {
var showDiv = document.getElementById("showDiv" + i);
// var textlistn = document.getElementById("textlistn");
if (showDiv.style.display === "none") {
showDiv.style.display = "block";
} else {
showDiv.style.display = "none";
}
}
}
<div>
<h2>Unit1</h2>
<% if(data.length >0) { %> <% for(var i=0;i< data.length;i++) {%>
<h5><%=data[i].id%>: <%=data[i].que%></h5>
<div class="container">
<div class="row">
<div class="col align-self-start">
<input type="radio" name="radio<%= i %>" value="A" /> 選項A:
<%=data[i].option.A%>
<br>
<input type="radio" name="radio<%= i %>" value="B" />選項B:
<%=data[i].option.B%>
<br>
<input type="radio" name="radio<%= i %>" value="C" />選項C:
<%=data[i].option.C%>
<br>
<input type="radio" name="radio<%= i %>" value="D" />選項D:
<%=data[i].option.D%>
</div>
<div class="col align-self-center">
</div>
<div class="col align-self-end">
<div id="showDiv<%= i %>" class="col align-self-end">
<p>答案: <%=data[i].answer%></p>
<p>翻譯: <%=data[i].translate%></p>
</div>
</div>
</div>
</div>
<% } %> <% } %>
<div class="container mx-2 my-2 py-5">
<button type="button" id="btn" class="btn btn-primary ">顯示答案</button>
</div>
<script src="/js/script.js"></script>
</div>
</div>