如何在 HTML 正文中调用 JavaScript 函数

How to call a JavaScript function within an HTML body

本文关键字:调用 JavaScript 函数 正文 HTML      更新时间:2023-09-26

我有一个填充表格的JavaScript函数:

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

我想在 HTML 正文中执行它。我已经尝试了以下内容,但它没有创建表。

<table>
    <tr>
        <th>Balance</th>
        <th>Fee</th>        
    </tr>
      createtable();
</table>

如何在 HTML 正文中执行此函数?

尝试将 createtable(); 语句包装在 <script> 标记中:

<table>
        <tr>
            <th>Balance</th>
            <th>Fee</th>
        </tr>
        <script>createtable();</script>
</table>

如果我是你,我会避免使用 document.write() 并使用 DOM。

首先将文件包含在 html 的 head 标签中,然后在正文标签下的脚本标签中调用函数,例如

要调用的 js 文件函数

function tryMe(arg) {
    document.write(arg);
}

网页文件

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

完成

只是为了澄清事情,你没有/不能"在HTML正文中执行它"。

您可以使用javascript修改HTML的内容。

你决定在什么时候执行javascript。

例如,下面是一个html文件的内容,包括javascript,它可以做你想要的。

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

享受!

尝试在脚本标签中使用 DOM 的 createChild() 方法或表对象的 insertRow() 和 insertCell() 方法。