How HTML calls JS
HTML (Hypertext Markup Language) and JS (JavaScript) are the two most basic and important technologies in Web development. HTML is mainly responsible for the structure and layout of web pages, while JS is mainly responsible for the functionality and interaction of web pages. In web development, we often need to let HTML call JS to implement various functions of web pages, such as form validation, dynamic loading of content, etc. This article will introduce how HTML calls JS methods.
Three ways to call JS in HTML
There are three main ways to call JS in HTML: inline, internal and external.
Inline is to embed JS code directly into HTML tags, for example:
<button onclick="alert('你点击了按钮')">点击我</button>
When this button is clicked, A prompt box will pop up because the onclick
attribute executes an embedded JS code. Although this method is simple, it is not conducive to maintenance and management. When the amount of code is large, it will become very cumbersome.
Internal style is to write JS code in the <head>
tag or <body> of the HTML document
<script> tag in the
tag, for example:
<html> <head> <title>内部式</title> <script> function test() { alert('你点击了按钮'); } </script> </head> <body> <button onclick="test()">点击我</button> </body> </html>
In this example, we write the JS code in the <head>
tag , and defines a function named test
. Then in the button tag in the HTML, call the test
function via onclick
. This approach is easier to maintain and manage than inline.
External style is to put the JS code in a separate JS file, and then pass it in the HTML document through <script>
Tag introduction. Suppose we write the JS code in a file named test.js
, then the calling method in HTML is as follows:
<html> <head> <title>外部式</title> <script src="test.js"></script> </head> <body> <button onclick="test()">点击我</button> </body> </html>
In this way, HTML will request test from the server .js
file and execute the JS code in it. This method is more modular and separated than the internal method, and has higher maintainability.
Summary
The three ways in which HTML calls JS all have their advantages and disadvantages. Although the inline style is concise and clear, it is not conducive to maintenance and management; the internal style is more maintainable, but the code may become too complex; the external style is modular and separated, and has the highest maintainability.
In actual applications, we should choose the most suitable calling method according to the actual situation of the project in order to achieve more efficient, stable and easier-to-maintain code.
The above is the detailed content of How to call js from html. For more information, please follow other related articles on the PHP Chinese website!