Como chamar uma função JavaScript dentro de um corpo HTML
tenho uma função JavaScript que preenche uma tabela:
<script>
var col1 = ["Full time student checking (Age 22 and under) ", "Customers over age 65", "Below $500.00"];
var col2 = ["None", "None", "$8.00"];
function createtable() {
<!--To fill the table with javascript-->
for (var j = 0; j < col1.length; j++) {
if (j % 2 == 0) {
document.write("<tr><td>" + col1[j] + " </td>");
document.write("<td>" + col2[j] + "</td></tr>");
} else {
document.write("<tr bgcolor='#aeb2bf'><td>" + col1[j] + " </td>");
document.write("<td>" + col2[j] + "</td></tr1>");
}
}
}
</script>
quero executá-lo dentro do corpo HTML. Tentei o seguinte, mas não cria a mesa.
<table>
<tr>
<th>Balance</th>
<th>Fee</th>
</tr>
createtable();
</table>
Como posso executar esta função dentro do corpo HTML?
4 answers
Tente embrulhar a declaração createtable();
numa marca <script>
:
<table>
<tr>
<th>Balance</th>
<th>Fee</th>
</tr>
<script>createtable();</script>
</table>
Eu evitaria usar o documento.escreve e usa o DOM se eu fosse a ti.
Primeiro incluir o ficheiro na marca principal do html, depois chamar a função em marcas de script sob marcas corporais, por exemplo
A função de ficheiro Js deve ser chamada
function tryMe(arg) {
document.write(arg);
}
FICHEIRO HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src='object.js'> </script>
<title>abc</title><meta charset="utf-8"/>
</head>
<body>
<script>
tryMe('This is me vishal bhasin signing in');
</script>
</body>
</html>
Terminar
Tente usar o método createChild () de DOM ou insertRow() e o método insertCell () de objeto de tabela em tag script.
Você pode modificar o conteúdo do HTML usando javascript.
Você decide em que ponto quer que o javascript seja executado.
Por exemplo, aqui está o conteúdo de um arquivo html, incluindo javascript, que faz o que você quer.
<html>
<head>
<script>
// The next line document.addEventListener....
// tells the browser to execute the javascript in the function after
// the DOMContentLoaded event is complete, i.e. the browser has
// finished loading the full webpage
document.addEventListener("DOMContentLoaded", function(event) {
var col1 = ["Full time student checking (Age 22 and under) ", "Customers over age 65", "Below $500.00" ];
var col2 = ["None", "None", "$8.00"];
var TheInnerHTML ="";
for (var j = 0; j < col1.length; j++) {
TheInnerHTML += "<tr><td>"+col1[j]+"</td><td>"+col2[j]+"</td></tr>";
}
document.getElementById("TheBody").innerHTML = TheInnerHTML;});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>Balance</th>
<th>Fee</th>
</tr>
</thead>
<tbody id="TheBody">
</tbody>
</table>
</body>
Divirtam-se !