从对象数组动态扩展表

时间:2014-10-27 17:02:21

标签: javascript jquery

正如标题所述,我正在尝试创建一个根据数组中对象数量动态扩展或缩小的表。这些对象中的每一个都有10个属性,这些属性都需要在不同的行中显示。我开始编写for循环来迭代数组并使用JQuery的.html()显示每个属性,并意识到当所有的说完成时它看起来会很混乱,但我不知道从哪里开始..完整的代码如下,但是我现在正在使用showResults函数..

//scripts
//Customer Object constructor
function CustomerObject(fName, lName, mName, address, city, state, zip, age, gender, pizza) {
    this.fName = fName;
    this.lName = lName;
    this.mName = mName;
    this.address = address;
    this.city = city;
    this.state = state;
    this.zip = zip;
    this.age = age;
    this.gender = gender;
    this.pizza = pizza;
}

//Array of CustomerObjest
var CustomerArray = new Array();

$(document).ready(function () {
    $("#TBFName").focus();
});

$("#BtnSave").click(function () {
    //When Save button is pressed.

    Validate();
}); 

$("#BtnReset").click(function () {
    //When Clear button is pressed
    ClearAllInfo();
});

$("#BtnDone").click(function () {
    //When Done button is pressed
    ShowResults();
});

$("#BtnMore").click(function () {
    //When Enter More button is pressed
    ShowResults();
    $("#DivFormContainer").show();
    $("#DivResults").hide();
});

$("#BtnMoreClearCustomers").click(function () {
    //When Clear All Customers button is pressed
    CustomerArray = new Array();
    $("#DivFormContainer").show();
    $("#DivResults").hide();
});

function Validate() {
    var isValid = true;
    var fstName = $("#TBFName").val();
    var mdlName = $("#TBMI").val();
    var lstName = $("#TBLName").val();
    var addrs = $("#TBAdress").val();
    var cit = $("#TBCity").val();
    var stat = $("#DDState").val();
    var zipCode = $("#TBZip").val();
    var gend = $("input:radio[name='RGGender']:checked").val();
    var old = $("#TBAge").val();
    var pza = $("input:radio[name='RGLikePizza']:checked").val();
    // Validation goes Here for All Fields


    if (isValid == true) { //If isValid is still true, no errors
        CustomerArray.push(new CustomerObject(fstName, lstName, mdlName, addrs, cit, stat, zipCode, old, gend, pza));
        $("#DivMessage").show();
        $("#DivMessage").html("Record Saved. Add a new record or press done to see results.");
        $("#DivMessage").fadeOut(1600);
    }
}


function ShowResults() {
    ClearAllInfo();
    $("#DivResults").show();
    $("#DivFormContainer").hide();
    //Code to display all customers information
    for (var i = 0; i < CustomerArray.length; i++) {

        $("#list").html(CustomerArray[i].fName + CustomerArray[i].lName +      CustomerArray[i].mName);
        //create table?
    }
}

function ClearResultsDiv() {
    $("#DivResults").html("");
}

function ClearAllInfo() {
    $("input[type=text]").val("");
    $("textarea").val("");
    $("select").prop('selectedIndex', 0);
    $(".error").html("");
    $("input[type=radio]").attr('checked', false);
}

2 个答案:

答案 0 :(得分:0)

这是直接DOM操作变得混乱的地方,你最好使用MVC框架。有很多可供选择:http://todomvc.com

我使用AngularJS做了一个简单的例子:

http://codepen.io/anon/pen/nuGwz?editors=101

好消息是,您只需要关心修改数据(客户数组)。视图(DOM)会自动更新。像这样:

$scope.CustomerArray.push({name: 'Joanna', age: '46', city: 'New York'});

答案 1 :(得分:0)

据我了解,您希望从包含行数据的数组生成表。

这是制作餐桌的一种方法:

var maketable = (function(){

    var elem, td, th, tr;

    elem = function(elemtype, children){
        var el = document.createElement(elemtype);
        children.forEach(function(child){
            el.appendChild(child);
        });
        return el;
    };

    td = function(s){
        return elem('td', [document.createTextNode(s)]);
    };

    th = function(s){
        return elem('th', [document.createTextNode(s)]);
    };

    tr = function(row){
        return elem('tr', row.map(td));
    };

    return function(data){
        var cols, rows, thead, tbody, table;
        cols = Object.keys(data[0]);
        rows = data.map(function(row){
            return Object.keys(data[0]).map(function(key){
                return row[key];
            });
        });
        thead = elem('thead', [elem('tr', cols.map(th))]);
        tbody = elem('tbody', rows.map(tr));
        table = elem('table', [thead, tbody]);
        return table;
    };
}());

使用示例:

var data = [{a: 'a0', b: 'b0'}, {a: 'a1', b: 'b1'}, {a: 'a2', b: 'b2'}];
var table = maketable(data);
document.body.appendChild(table);