Home  >  Article  >  Web Front-end  >  JavaScript basic output and embedded writing tutorial_Basic knowledge

JavaScript basic output and embedded writing tutorial_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 15:36:021201browse

JavaScript does not have any printing or output functions.
In HTML, JavaScript is commonly used to manipulate HTML elements.
Manipulate HTML elements
To access an HTML element from JavaScript, you can use the document.getElementById(id) method.
Please use the "id" attribute to identify HTML elements and innerHTML to get or insert element content:
Example

<!DOCTYPE html>
<html>
<body>

<h1>我的第一个 Web 页面</h1>

<p id="demo">我的第一个段落</p>

<script>
document.getElementById("demo").innerHTML = "段落已修改。";
</script>

</body>
</html>

The above JavaScript statement (in the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag) can be executed in a web browser:

  • document.getElementById("demo") is JavaScript code that uses the id attribute to find an HTML element.
  • innerHTML = "Paragraph changed." is the JavaScript code used to modify the HTML content (innerHTML) of the element.

Write to HTML document
For testing purposes, you can write JavaScript directly in the HTML document:
Example

<!DOCTYPE html>
<html>
<body>

<h1>我的第一个 Web 页面</h1>

<p>我的第一个段落。</p>

<script>
document.write(Date());
</script>

</body>
</html>

Please use document.write() to only write content to the document.
If document.write is executed after the document has finished loading, the entire HTML page will be overwritten.
Example

<!DOCTYPE html>
<html>
<body>

<h1>我的第一个 Web 页面</h1>

<p>我的第一个段落。</p>

<button onclick="myFunction()">点我</button>

<script>
function myFunction() {
document.write(Date());
}
</script>

</body>
</html>

Write to console
If your browser supports debugging, you can use the console.log() method to display JavaScript values ​​in the browser.
Use F12 in the browser to enable debug mode, and click the "Console" menu in the debug window.
Example

<!DOCTYPE html>
<html>
<body>

<h1>我的第一个 Web 页面</h1>

<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>

</body>
</html>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn