How to use DOM function in EJS

问题: I'm trying to make a function in a webpage when a user press the 'submit' button it goes into an EJS function but I need the DOM function to change elements but the documen...

问题:

I'm trying to make a function in a webpage when a user press the 'submit' button it goes into an EJS function but I need the DOM function to change elements but the document is not defined in EJS what can I do.

<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>

回答1:

ejs is a template language, which means it only controls how the page is rendered, and does nothing to change what happens to the page on the client's browser after it has loaded.

Changing your code to this should fix the problem:

<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>
  • 发表于 2019-03-10 23:56
  • 阅读 ( 67 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除