Não é possível adicionar dinamicamente linhas a uma no IE?

StackOverflow https://stackoverflow.com/questions/812693

Pergunta

Eu tenho um aplicativo AJAX que os downloads de um objeto JSON e usa os dados para adicionar linhas a uma HTML

usando funções Javascript DOM. Ele funciona perfeitamente ... exceto no Internet Explorer. IE não dá qualquer tipo de erro, e eu tenho verificado o melhor que eu puder que o código está sendo executado pelo navegador, mas ele simplesmente não tem efeito. Eu criei esta página rápida e suja para demonstrar o 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>

Eu não tentei IE 8, mas o IE 7 e IE 6 não mostram as linhas adicionais que são supostamente sendo adicionados. Não consigo entender o porquê. Alguém sabe uma boa solução para este problema, ou estou talvez fazendo algo errado?

Foi útil?

Solução

Você precisa criar um elemento TBODY para adicionar seu novo TR a e adicione o TBODY para a sua mesa, como este:

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

Outras dicas

Aparentemente, no IE você precisa anexar a sua linha para o elemento tbody, e não o elemento da tabela ... Veja a discussão em Rubi-Forum .

Expandindo a discussão lá, o

marcação é geralmente feito sem explícita e marcação, mas o elemento é onde você realmente precisa adicionar a sua nova linha, como
faz não contém elementos diretamente.

Edit: agora funciona no IE! insertSiblingNodesAfter usa o parentNode do irmão, que passa a ser um tbody no IE


É difícil saber o que peculiaridades estão na loja quando você tenta manipular o cross-browser DOM. Eu recomendo que você use uma biblioteca existente que foi totalmente testado em todos os principais navegadores, e é responsável por peculiaridades.

Pessoalmente eu uso MochiKit, você pode mergulhar em manipulação DOM aqui: http://mochikit.com/doc/html/MochiKit/DOM.html

A sua função final poderia ser algo como isto:

function addEmployee(employeeName, employeeJob) {
    var trs = getElementsByTagAndClassName("tr", null, "employeetable");
    insertSiblingNodesAfter(trs[trs.length-1], TR({}, TD({}, employeeName), TD({}, employeeJob));
    alert("code executed!");
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top