简体   繁体   中英

having trouble removing an extra row from a dynamically created table

I'm trying to dynamically create a table using JS and jQuery. (I know I can hard code it in html but I don't want to do that.)
I have an extra row at the table that I'm having trouble removing.
Can someone please provide an answer/answers on how best to solve this in my code?

My code is posted below.

var game = {
    matrix: [],
    startGame: function()
    {
        this.doDomStuff(); //build board
    },
    doDomStuff: function(row, column)
    {
        for(var i = 0; i < 7; i++)
        {
            var row = $('<div>');
            row.attr('id', 'data-row' + (i + 1));
            row.addClass('data-row');
            for(var j = 0; j < 6; j++)
            {
                var column = $('<div>');
                column.attr('id', 'data-column' + (j + 1));
                column.addClass('data-column');
                column.addClass('column');
                row.append(column);
            }
            $('body').prepend(row);
        }
    }
};

If you are making a game, and each row can have its own logic and behaviour, so it will be faster to operate array neither DOM structure. If your logic will be more complecated, you will see the difference in perfomance. So, call the DOM structure if you are really need to update objects there. For example:

function SuperTable(){
    this.tablerows = [];
    this.DOMObject = $("body");
}

SuperTable.prototype.AddRow = function() {
    this.tablerows[this.tablerows.length] = new SuperRow(this.tablerows.length,this.DOMObject);
}

SuperTable.prototype.RemoveRow = function(rowIndex) {
    this.tablerows[rowIndex].DOMObject.remove(); // remove element from DOM
    this.tablerows.splice(rowIndex,1); // remove element from logic of the game
}

function SuperRow(rownumber,parent) {
    this.DOMObject = $("<div>");
    this.DOMObject.addClass('data-row');
    parent.prepend(this.DOMObject);
}

mytable = new SuperTable()
mytable.AddRow() // create row on 0 position
mytable.RemoveRow(0) // remove row from 0 position

You can use JQuery's .remove() function. For example, if you want to remove the last row: $("#data-row7").remove()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM