在Node – Express中,在POST操作后更改EJS中的元素样式

我有一个表单页面,应该在用户填写表单并点击提交button后显示成功提醒(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; } 

在Node-Express的POST操作之后,如何将display属性更改为not none (block,inline,inline-block),以便显示成功警报消息?

 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中,只有在validation后

 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>