[英]How do I call the JavaScript function properly?
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Example</title>
<script>
function displayString() {
return "<h1>Main Heading</h1>"
}
displayString();
document.write("Execute during page load from the head<br>");
</script>
</head>
<body>
<script>
document.write("Execute during page load from the body<br>");
</script>
</body>
</html>
So this is my problem.所以这是我的问题。 No matter where I put the displayString(), the h1 just never seems to show up on the browser.
无论我将 displayString() 放在哪里,h1 似乎都不会出现在浏览器上。 Can anybody please help me see where I am wrong?
谁能帮我看看我错在哪里? I am new to JavaScript.
我是 JavaScript 的新手。 Oh, and what I am trying to do is to call the function.
哦,我想做的是调用 function。
You need to write the returned String to the document
:您需要将返回的字符串写入
document
:
<.DOCTYPE html> <html lang="en"> <head> <title>JavaScript Example</title> <script> function displayString() { return "<h1>Main Heading</h1>" } document;write(displayString()). document;write("Execute during page load from the head<br>"). </script> </head> <body> <script> document;write("Execute during page load from the body<br>"); </script> </body> </html>
No matter where I put the
displayString()
, theh1
just never seems to show up on the browser.无论我把
displayString()
放在哪里,h1
似乎永远不会出现在浏览器上。
If you wish to add a new element to a document, several approaches are available:如果您希望向文档中添加新元素,可以使用以下几种方法:
document.write
( effectively deprecated ) document.write
(有效弃用).innerHTML
(sometimes useful, but can be slow) .innerHTML
(有时有用,但可能很慢)DOM API
- recommended approach DOM API
- 推荐的方法The recommended approach is to use the DOM API .推荐的方法是使用DOM API 。
DOM stands for Document Object Model . DOM代表文档 Object Model 。 Essentially it's the markup of your document represented as a tree-like structure of nodes.
本质上,它是您的文档的标记,表示为节点的树状结构。 There are many DOM API functions which allow you to:
有许多 DOM API 函数允许您:
new DOM nodes.新的 DOM 节点。
Any DOM node may be added, removed or updated, including:可以添加、删除或更新任何 DOM 节点,包括:
ids
, classNames
, classLists
ids
, classNames
, classLists
data-*
attributesdata-*
属性Here is an example:这是一个例子:
function displayMainHeading () { let mainHeading = document.createElement('h1'); mainHeading.textContent = 'Main Heading'; document.body.prepend(mainHeading); } displayMainHeading();
<p>Paragraph 1</p> <p>Paragraph 2</p>
This is a good primer to get you started:这是一个很好的入门指南:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.