0
I created a table via javascript by manipulating elements of an array, which is all right, but I can only add the table in the DOM by a common function or an anonymous Jquery function, but when the anonymous function is javascript, it cannot add the table to the DOM...
done with anonymous function js (does not work):
(function(){
const alunos = [
{ nome: 'Ana', nota: 9.1 },
{ nome: 'Bianca', nota: 8.4 },
{ nome: 'Carlos', nota: 7.6 },
{ nome: 'Julia', nota: 9.7 }
]
const linhas = alunos.map(aluno => {
const tdNome = `<td>${aluno.nome}</td>`
const tdNota = `<td>${aluno.nota}</td>`
return '<tr>' + tdNome + tdNota + '</tr>'
})
const tabela = linhas.reduce((tabela, elemendo) => tabela + elemendo ,'')
document.getElementById('conteudo').insertAdjacentHTML('beforeend', `<table>${tabela}</table>`)
})
done with common function in js (works):
function criarTabela(){
const alunos = [
{ nome: 'Ana', nota: 9.1 },
{ nome: 'Bianca', nota: 8.4 },
{ nome: 'Carlos', nota: 7.6 },
{ nome: 'Julia', nota: 9.7 }
]
const linhas = alunos.map(aluno => {
const tdNome = `<td>${aluno.nome}</td>`
const tdNota = `<td>${aluno.nota}</td>`
return '<tr>' + tdNome + tdNota + '</tr>'
})
const tabela = linhas.reduce((tabela, elemendo) => tabela + elemendo ,'')
document.getElementById('conteudo').insertAdjacentHTML('beforeend', `<table>${tabela}</table>`)</table>`)
}
criarTabela()
done with anonymous Jquery function (works):
$(function (){
const alunos = [
{ nome: 'Ana', nota: 9.1 },
{ nome: 'Bianca', nota: 8.4 },
{ nome: 'Carlos', nota: 7.6 },
{ nome: 'Julia', nota: 9.7 }
]
const linhas = alunos.map(aluno => {
const tdNome = $('<td>').html(aluno.nome)
const tdNota = $('<td>').html(aluno.nota)
return $('<tr>').append(tdNome, tdNota)
})
const tabela = $('<table>').append(linhas)
.css("border", "solid 5px")
$('#conteudo').append(tabela)
})
html has nothing special, just a div with an ID:
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>tabelo feita de um objeto</title>
<link rel='stylesheet' href='css/estilo.css'>
<script src='js/jquery.js'></script>
</head>
<body class='conteudo exercicio'>
<h1>criando tabela</h1>
<div id='conteudo'></div>
This is just a syntax error. You are declaring the function but you are not invoking it. Add a couple of parentheses at the end of the statement, it should stay that way:
(function() { /* ... */ })()
– Andre
that’s right, I was confusing the syntax of Jquery with that of JS. thank you!
– lucas F
I think the function is simply not to be called, use () to call it and then the Brackets.
– ScrapBench
yes, that’s exactly it, I confused the syntax of jquery with that of js. thanks :D
– lucas F