简体   繁体   English

如何正确调用 JavaScript function?

[英]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() , the h1 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 函数允许您:

  • add添加
  • remove消除
  • append append
  • prepend前置
  • insert插入
  • update更新

new DOM nodes.新的 DOM 节点。

Any DOM node may be added, removed or updated, including:可以添加、删除或更新任何 DOM 节点,包括:

  • parent elements父元素
  • child elements子元素
  • sibling elements兄弟元素
  • element attributes元素属性
  • ids , classNames , classLists idsclassNamesclassLists
  • custom data-* attributes自定义data-*属性
  • text nodes文本节点

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>


Further Reading延伸阅读

This is a good primer to get you started:这是一个很好的入门指南:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM