我正在尝试在网页中创建一个功能,当用户按下“提交”按钮时它会进入EJS功能,但我需要DOM功能来更改元素但是文档没有在EJS中定义我该怎么做。
<p id="resMessage"></p>
<div id="generalSettings" class="main-menu-content">
<% if (showData.prefix) { %>
<%
function savePrefix() {
try {
configData({
'prefix': document.getElementById('resMessage') <=== this is not defined
});
%>
<script type="text/javascript">
var resMessage = document.getElementById("resMessage")
resMessage.style.backgroundColor = 'green';
resMessage.innerHTML = "Success!"
</script>
<%
} catch (err) {
if (err) {
%>
<script type="text/javascript">
var resMessage = document.getElementById("resMessage")
resMessage.style.backgroundColor = 'red';
resMessage.innerHTML = `Error: ${err.toString()}`
</script>
<%
console.log(err)
};
};
};
%>
<input type="text" id="prefix" value=<%= showData.prefix %> maxlength="6"><input type="submit" onclick=<%= savePrefix() %>>
<% } %>
</div>
ejs是一种模板语言,这意味着它只控制页面的呈现方式,并且在加载后不会改变客户端浏览器页面上发生的事情。
将代码更改为此应解决问题:
<p id="resMessage"></p>
<div id="generalSettings" class="main-menu-content">
<% if (showData.prefix) { %>
<script type="text/javascript">
function savePrefix() {
try {
configData({
'prefix': document.getElementById('resMessage')
});
var resMessage = document.getElementById("resMessage")
resMessage.style.backgroundColor = 'green';
resMessage.innerHTML = "Success!"
} catch (err) {
var resMessage = document.getElementById("resMessage")
resMessage.style.backgroundColor = 'red';
resMessage.innerHTML = `Error: ${err.toString()}`
console.log(err);
}
}
</script>
<input type="text" id="prefix" value="<%= showData.prefix %>" maxlength="6"><input type="submit" onclick="<%= savePrefix() %>">
<% } %>
</div>