【问题标题】:Change element style in EJS after POST action in Node - Express在 Node 中的 POST 操作后更改 EJS 中的元素样式 - Express
【发布时间】:2017-07-01 04:23:10
【问题描述】:

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

如何将显示属性更改为 not none (block, inline, inline-block) 以便在 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。

【问题讨论】:

    标签: javascript css node.js express ejs


    【解决方案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>
    <% } %>
    

    上述方法也可以用于错误。

    方法二:

    更改 CSS 有点过于复杂,您可以更改类或 ID。 (总是改变类,而不是 ids)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-11
      • 2016-05-18
      • 1970-01-01
      • 2022-08-12
      • 2021-10-11
      • 2017-04-06
      • 1970-01-01
      • 2016-02-09
      相关资源
      最近更新 更多