Pregunta

Tengo una aplicación AJAX que descarga un objeto JSON y usa los datos para agregar filas a un HTML < table > utilizando las funciones de Javascript DOM. Funciona perfectamente ... excepto en Internet Explorer. IE no da ningún tipo de error, y he verificado que el código está siendo ejecutado por el navegador, pero simplemente no tiene ningún efecto. Creé esta página rápida y sucia para demostrar el problema:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><title></title></head><body>

<table id="employeetable">
    <tr>
        <th>Name</th>
        <th>Job</th>
    </tr>
</table>

<script type="text/javascript">
    function addEmployee(employeeName, employeeJob) {
        var tableElement = document.getElementById("employeetable");
        if (tableElement) {
            var newRow = document.createElement("tr");
            var nameCell = document.createElement("td");
            var jobCell = document.createElement("td");
            nameCell.appendChild(document.createTextNode(employeeName));
            jobCell.appendChild(document.createTextNode(employeeJob));
            newRow.appendChild(nameCell);
            newRow.appendChild(jobCell);
            tableElement.appendChild(newRow);
            alert("code executed!");
        }
    }

    setTimeout("addEmployee(\"Bob Smith\", \"CEO\");", 1000);
    setTimeout("addEmployee(\"John Franks\", \"Vice President\");", 2000);
    setTimeout("addEmployee(\"Jane Doe\", \"Director of Marketing\");", 3000);
</script>

</body></html>

No he probado IE 8, pero tanto IE 7 como IE 6 no muestran las filas adicionales que supuestamente se están agregando. No puedo entender por qué. ¿Alguien sabe una buena solución a este problema, o quizás estoy haciendo algo mal?

¿Fue útil?

Solución

Necesitas crear un elemento TBODY para agregar tu nuevo TR y luego agregar el TBODY a tu tabla, como esto:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><title></title></head><body>

<table id="employeetable">
    <tr>
        <th>Name</th>
        <th>Job</th>
    </tr>
</table>

<script type="text/javascript">
    function addEmployee(employeeName, employeeJob) {
        var tableElement = document.getElementById("employeetable");
        if (tableElement) {
            var newTable = document.createElement('tbody');   // New
            var newRow = document.createElement("tr");
            var nameCell = document.createElement("td");
            var jobCell = document.createElement("td");
            nameCell.appendChild(document.createTextNode(employeeName));
            jobCell.appendChild(document.createTextNode(employeeJob));
            newRow.appendChild(nameCell);
            newRow.appendChild(jobCell);
            newTable.appendChild(newRow);   // New
            tableElement.appendChild(newTable);   // New
            alert("code executed!");
        }
    }

    setTimeout("addEmployee(\"Bob Smith\", \"CEO\");", 1000);
    setTimeout("addEmployee(\"John Franks\", \"Vice President\");", 2000);
    setTimeout("addEmployee(\"Jane Doe\", \"Director of Marketing\");", 3000);
</script>

</body></html>

Otros consejos

Aparentemente, en IE necesitas adjuntar tu fila al elemento TBody, no al elemento Table ... Consulte la discusión en Ruby-Forum .

Ampliando la discusión allí, la tabla < table > Generalmente, el marcado se realiza sin < thead > y < tbody > marcado, pero el < tbody > ELEMENT es donde realmente necesita agregar su nueva fila, como < table > no contiene < tr > elementos directamente.

Editar: ahora funciona en IE! insertSiblingNodesAfter usa el parentNode del hermano, que resulta ser un cuerpo en IE


Es difícil saber qué peculiaridades hay en la tienda cuando intentas manipular el navegador cruzado DOM. Le recomiendo que use una biblioteca existente que haya sido probada en su totalidad en todos los principales navegadores y cuentas para las peculiaridades.

Personalmente uso MochiKit, puedes sumergirte en la manipulación de DOM aquí: http://mochikit.com/doc/html/MochiKit/DOM.html

Su función final podría verse así:

function addEmployee(employeeName, employeeJob) {
    var trs = getElementsByTagAndClassName("tr", null, "employeetable");
    insertSiblingNodesAfter(trs[trs.length-1], TR({}, TD({}, employeeName), TD({}, employeeJob));
    alert("code executed!");
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top