提升节点js中的降幅功能

时间:2018-12-05 20:37:23

标签: node.js express pug

我很难找到在前端和后端表达Pug(jade)来实现upvote / downvote功能的好方法。我当前的设置如下所示。我在mongo数据库中遍历项目以显示评分项目。

each val in post['listitem']
    div.listitem
       .rating_button
         .buttons
           button(class='up' aria-pressed="false") Upvote
           p#vote 0 //currently 0 later data from db
           button(class='down' ariapressed="false")Downvote

然后我对我的api进行了客户端ajax调用

$(document).ready(function(){
    $(document).on('click', '.up', function(){
        var up = $.post("/api/:id/upvote", {changeBy: 1}, function(dataBack){
            $("#vote").text(dataBack); 
        });
    });
    $(document).on('click', '.down', function(){
        var down = $.post("/api/:id/downvote", {changeBy: 1},
        function(dataBack){
            $("#vote").text(dataBack);
        });
      });
    });

Api看起来像这样-首先是siteController

exports.upvote = async (req, res) => {
res.setHeader("Content-Type", "application/json");
vote += parseFloat(req.body.changeBy);
res.write(JSON.stringify(vote));
res.end();
console.log(vote);}

exports.downvote = async (req, res) => {
res.setHeader("Content-Type", "application/json");
vote -= parseFloat(req.body.changeBy);
res.write(JSON.stringify(vote));
res.end();
console.log(vote);}

第二个我的index.js

router.post('/api/:id/upvote', siteController.upvote);
router.post('/api/:id/downvote', siteController.downvote);

一切正常,但是使用此设置后,循环中的按钮无法正常工作。只有第一个按钮将数字增加/减少1。

如何解决循环中的按钮问题?还有改善当前设置的灵感/想法吗?

1 个答案:

答案 0 :(得分:0)

您需要以某种方式将ID传递给onclick函数。一种方法是像这样设置clicking元素的ID:

each val in post['listitem']
    div.listitem
       .rating_button
         .buttons
           button(id= val.id class='up' aria-pressed="false") Upvote
           p#vote 0 //currently 0 later data from db
           button(id= val.id class='down' ariapressed="false")Downvote

然后通过在click函数中添加对元素的引用来捕获该信息:

$(document).on('click', '.up', function(element){

    var id = element.target.id;

    var up = $.post("/api/" + id + "/upvote", {changeBy: 1}, function(dataBack){
        $("#vote").text(dataBack);
    });
});