2009-05-01 7 views
21

Tengo una aplicación AJAX que descarga un objeto JSON y usa los datos para agregar filas a una tabla HTML < > usando las funciones DOM de Javascript. Funciona perfectamente ... excepto en Internet Explorer. IE no da ningún tipo de error, y he verificado lo mejor que puedo que el código está siendo ejecutado por el navegador, pero simplemente no tiene ningún efecto. He creado esta página rápida y sucia para demostrar el problema:¿No se pueden agregar dinámicamente filas a un <TABLE> en IE?

<!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 el IE 8, pero ambos IE 7 e IE 6 no muestran las filas adicionales que se están agregando supuestamente. No puedo entender por qué. ¿Alguien sabe una buena solución a este problema, o quizás estoy haciendo algo mal?

Respuesta

17

Es necesario crear un elemento TBODY añadir su nueva TR y luego añadir el TBODY a su mesa, así:

<!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> 
+3

en realidad, 'tableElement.getElementsByType ('tbody')' debería devolver lo que se desea aquí .... –

+0

en realidad,

tableElement.getElementsByType('tbody')
debería devolver lo que se desea aquí –

+0

Lo siento chicos, todavía un poco nuevo en las diferencias de sintaxis de comentario/respuesta. Obviamente, quería poner formato de estilo de código en el fragmento de código. –

2

Editar: ¡ahora funciona en IE! insertSiblingNodesAfter utiliza el parentNode del hermano, que pasa a ser un tbody en IE


Es difícil saber qué peculiaridades están en el almacén cuando intenta manipular el DOM a través del navegador. Le recomendaría que use una biblioteca existente que ha sido completamente probada en todos los principales navegadores y cuenta para las peculiaridades.

Personalmente utilizo MochiKit, se puede bucear en la manipulación DOM aquí: http://mochikit.com/doc/html/MochiKit/DOM.html

Su función final podría ser algo como esto:

function addEmployee(employeeName, employeeJob) { 
    var trs = getElementsByTagAndClassName("tr", null, "employeetable"); 
    insertSiblingNodesAfter(trs[trs.length-1], TR({}, TD({}, employeeName), TD({}, employeeJob)); 
    alert("code executed!"); 
} 
+0

jQuery es otra muy buena alternativa al código liados a mano. – GalacticCowboy

+0

+1 por usar MochiKit (mi biblioteca favorita), pero te perdiste la respuesta real: necesita agregar filas a un TBody para que IE reconozca las filas. –

+0

No me di cuenta de que appendChildNodes no funcionaba. He estado utilizando insertSiblingNodes en mi propio código, lo que funciona. He actualizado la respuesta para que refleje una solución funcional. – EoghanM

8

Al parecer, en el IE necesita para anexar su fila para el elemento TBody, no el elemento Tabla ... Consulte la discusión en Ruby-Forum.

Ampliando la discusión allí, la mesa <> marcado se hace generalmente sin explícita la culata en T> y < tbody> marcado <, pero el < tbody> elemento es donde realmente se necesita añadir su nueva fila, como < mesa> no contiene < tr> elementos directamente.

+3

Agregar a tbody funciona constantemente en todos los navegadores, por lo que es seguro hacerlo siempre. – JPot

Cuestiones relacionadas