如何在 HTML 正文中调用 JavaScript 函数
How to call a JavaScript function within an HTML body
我有一个填充表格的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() 方法。
相关文章:
- 我需要从php调用javascript或jquery
- 如何在webView,Android中从@JavascriptInterface方法调用Javascript
- 使用html表单中的参数调用JavaScript函数
- 可以´t调用JavaScript中的函数
- 在按钮上调用Javascript函数
- 如何从Objective-C代码中调用javascript代码
- 当库在页脚中加载时,基于PHP条件调用Javascript
- 可以't在Jasmine中调用Javascript函数
- 在page_load事件上调用javascript函数
- 如何在ajax中调用javascript对象的方法
- 如何使用WPF调用JavaScript对象的函数
- 我们可以用参数对象集合而不是原始数据来调用JavaScript collection.reduce()方法吗
- 在新的浏览器选项卡上加载新的aspx页面后调用JavaScript函数
- 从附加文本调用javascript(订单车)
- 在线程循环中调用JavaScript
- 在指定时间后多次调用Javascript中的函数
- 未调用Javascript onscroll事件
- 如何正确调用Javascript中的匿名函数
- 从字符串调用javascript函数
- 无法从活动调用 javascript 函数