在节点 - 快速的开机自检操作后更改 EJS 中的元素样式



我有一个表单页面,在用户填写表单并点击"提交"按钮后,应该会显示成功警报(Boostrap(。

<form class="well form-horizontal" action="/contact" method="post"  id="contact_form">
... (input fields here)
<div class="alert alert-success" role="alert" id="success_message"> Success 
  <i class="glyphicon glyphicon-thumbs-up" ></i> Thanks for contacting us, we will get back to you shortly. 
</div>
<div class="form-group">
  <label class="col-md-3 control-label"></label>
  <div class="col-md-6">
    <button type="submit" class="btn btn-warning" > Submit <span class="glyphicon glyphicon-send"></span></button>
  </div>
</div>

默认情况下,在我的 CSS 中:

#success_message { display: none; }

如何将显示属性更改为不none(块、内联、内联块(,以便在 Node-Express 中的 POST 操作之后显示成功警报消息?

var router = express.Router();
router.post('/', function(req, res, next) {
    const data = {
        fname: req.body.name,
        lname: req.body.lname,
        ...
        comment: req.body.comment
    }
    // insert data using SQL/MongoDB library
    // refresh same page if success, the input elements cleared
    // and show the success alert or fail alert div in rendered HTML
        res.render('contact', {  
            fname :     ''
            lname :     ''
            ...
            comment : ''
        });
});

没有jQuery可以做到这一点吗?我不喜欢使用jQuery。

方法 1:

首先在 GET 请求中添加要呈现的 success 属性。

router.get('/', function(req, res, next) {
...
...
    res.render('contact', {
        fname: '',               
        ........
        success: false
    });
});

并在 POST 中,仅在验证后

router.post('/', function(req, res, next) {
    ...
    ...
        res.render('contact', {
            fname: '',               
            ........
            success: true
        });
    });

在你的 ejs 文件中,你可以做类似的事情

<% if (success) { %>
    <div class="alert alert-success" role="alert" id="success_message"> Success 
      <i class="glyphicon glyphicon-thumbs-up" ></i> Thanks for contacting us, we will get back to you shortly. 
    </div>
<% } %>

上述方法也可用于错误。

方法2:

更改CSS有点太复杂了,您可以更改类或id。(始终更改类,而不是 ID(

#id1 {
... 
}
#id2 {
...
}
<div class="alert alert-success" role="alert" id=<%= success ? "id1" : "id2" %>> Success 
  <i class="glyphicon glyphicon-thumbs-up" ></i> Thanks for contacting us, we will get back to you shortly. 
</div>

最新更新