使用Jade/Jquery更改表单

Change form using Jade/Jquery

本文关键字:表单 Jquery Jade 使用      更新时间:2023-09-26

我正在尝试让一个表单更改其选项以响应另一个事件。蛋糕需要在.sweet更改时更新,但蛋糕最初是通过res.render的,我不知道如何在不重新加载页面的情况下更改它。我只是这方面最好的ajax解决方案。

应用程序:

res.render('index', {cakes: json_object});

正文:

form(name="myform")
    div.input
        each item in cakes.topping
            input(type="checkbox", name=item.color)
            | #{item.color}

尝试换蛋糕:

磁头:

$(document).ready(function(){
    //requesting new Object
    $(".sweet").change(function () {
        socket.emit('choose', {sweet: $("#cho_swe").val()});
    });
    //getting new object
    socket.on('set_sweet', function(object){
         -- object is a new JSON which needs to replace cakes in the form below
    });
});        

如何将我的新对象转换为可以在循环中使用的格式?

注意:将把jade称为pug,以纪念他们被迫更换的品牌

当您在应用程序文件中呈现Pug时,Pug会在后端进行编译。然而,您正在与渲染文件并行发送额外的变量,pug对此没有任何作用域。

当您渲染它时,您将无法访问Pug函数

每个

item in cakes.topping

现在是

<input 1/>
<input 2/>
etc...

在这一点上,Pug已经完成了它的工作,现在这是一个前端问题。你不能使用pug的循环函数,你需要依靠前端框架或库来使内容动态。

有几种方法可以处理这个问题,但我看到你正在使用jquery,所以我们可以走那条路:

接收套接字广播时重新填充元素:

$(document).ready(function(){
    //get the form element
    $form = $('form[name="myform"]').empty();
    //requesting new Object
    $(".sweet").change(function () {
        socket.emit('choose', {sweet: $("#cho_swe").val()});
    });
    //getting new object
    socket.on('set_sweet', function(object){
    //
    // clear the current form and add the new html
    // if you know most of the html before hand and just have a few dynamic
    // fields consider having them in the pug template with 
    // display: none;
    //
        // dynamically add new elements without needing a page reload
        object.forEach(function(val, key) {
            $form.append('<div>'
                   +' <input type="checkbox" onclick="someClickHandler()" name="' + val + '"/>'
                   +' <div>' + val + '</div>'
                   +' </div>');
        });
    });
}); 

如果你发现自己需要做很多动态内容,可以考虑使用angularjs这样的框架。

上述有角度的解决方案类似于:

form(name="myform")
    div.input
        div(ng-repeat="item in items")
            input(type="checkbox", name=item.color)
            | #{item.color}
socket.on('set_sweet', function(object){
     $scope.items = object;
});

总之,pug将在后端编译一个页面,其中包含所有可用的内容、变量和所有内容,但一旦它被传递和呈现,你就要在前端让内容变得动态。