简体   繁体   中英

Animating adding a table row (JavaScript + jQuery)

I've written some code to add a table row which you can see below.

function addRow(pos) {

// Insert new HTML table row
var tblObj = document.getElementById('questionTbl');
var newRow = tblObj.insertRow(pos + 1);  

// Add new table cells
var newCell1 = newRow.insertCell(0);
newCell1.innerHTML = 'one';

var newCell2 = newRow.insertCell(1);
newCell2.innerHTML = 'two';

var newCell3 = newRow.insertCell(2);
newCell3.innerHTML = 'three';

var newCell4 = newRow.insertCell(3);
newCell4.innerHTML = 'four';

var newCell5 = newRow.insertCell(4);
newCell5.innerHTML = 'five';

var newCell6 = newRow.insertCell(5);
newCell6.innerHTML = 'six';

var newCell7 = newRow.insertCell(6);
newCell7.innerHTML = 'seven';

I have since added the jQuery library as I wanted some functionality that I haven't forseen (otherwise I would've done the Add Row stuff in query).

newRow.id = "row_" + (pos + 1);
newRow.className = "hide";

$(document).ready(function() {
    $("#row_" + (pos + 1)).switchClass("hide", "show-row");
});

The adding of the row works, but it doesn't animate. There is a delay in it appearing (which I guess would be the time it takes to animate).

Does anyone know why the animation isn't working?

Thanks.

Try this

$(document).ready(function() {
    $("#row_" + (pos + 1)).removeClass("hide").addClass("show-row").hide().show('slow');
});

Try this:

function addRow(pos) {

    // Insert new HTML table row
    var tblObj = document.getElementById('questionTbl');
    var newRow = tblObj.insertRow(pos + 1);  

    // Add new table cells
    var newCell1 = newRow.insertCell(0);
    newCell1.innerHTML = 'one';

    var newCell2 = newRow.insertCell(1);
    newCell2.innerHTML = 'two';

    var newCell3 = newRow.insertCell(2);
    newCell3.innerHTML = 'three';

    var newCell4 = newRow.insertCell(3);
    newCell4.innerHTML = 'four';

    var newCell5 = newRow.insertCell(4);
    newCell5.innerHTML = 'five';

    var newCell6 = newRow.insertCell(5);
    newCell6.innerHTML = 'six';

    var newCell7 = newRow.insertCell(6);
    newCell7.innerHTML = 'seven';

    newRow.id = "row_" + (pos + 1);
    newRow.className = "hide";

    $("#row_" + (pos + 1)).switchClass("hide", "show-row");
}

$(document).ready(function() { ... } should be used when you need code executed as soon as the DOM is ready to be manipulated, basically the function passed to the ready function is executed on page load. The original jQuery code would never execute as the function was attached to the ready event after the ready event had already been fired.

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