使用Jade/Jquery更改表单

3

我想让一个表单根据其他事件的响应而改变其选项。当选择“sweet”时,需要更新蛋糕选项,但是最初的蛋糕选项是通过res.render传递的,我不知道如何在不重新加载页面的情况下更改它。我希望使用最佳的ajax解决方案。

app:

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

body:

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
    });

});        

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

1

注意:为了尊重他们的品牌更名,将把Jade称为Pug。

Pug在您的应用程序文件中呈现时,在后端进行编译。但是,您会与呈现的文件并行发送其他变量,而Pug无法控制这些变量。

当您呈现它时,将无法访问Pug函数

each

item in cakes.topping

现在是

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

此时,Pug的工作已经完成,现在是前端问题。您无法使用Pug的循环功能,需要依靠前端框架或库使内容动态化。

有几种处理方法,但我看到您正在使用jquery,所以我们可以选择这条路:

当接收到socket广播时重新填充元素:

$(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这样的框架。使用angular的解决方案类似于:
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 将在后端编译页面,并使用所有可用的变量等内容,但一旦传递并呈现,你需要在前端使内容动态。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接