Basic usage of JavaScript

JavaScript is a programming language widely used in web development to make web pages more interactive and dynamic. Here are some basic uses of JavaScript:

  1. Embedding JavaScript in HTML
    JavaScript code is usually placed in HTML files

Example: Using JavaScript in HTML files

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript 示例</title>
    <script>
        // 这里是 JavaScript 代码
        function sayHello() {
      
      
            alert("Hello, world!");
        }
    </script>
</head>
<body>

    <h1>我的第一个 JavaScript 页面</h1>
    <button onclick="sayHello()">点击这里</button>

</body>
</html>
  1. Basic syntax and structure
    The basic syntax of JavaScript includes variable declaration, control structure, function, etc.

Variable Declaration
In JavaScript, you can declare variables using var, let, or const.

let message = "Hello, world!";
const pi = 3.14159;

Control structures
JavaScript supports standard control structures, such as if-else statements, for loops, while loops, etc.

if (condition) {
    
    
    // 条件为真时执行
} else {
    
    
    // 条件为假时执行
}

for (let i = 0; i < 10; i++) {
    
    
    // 循环 10 次
}

Functions
A function is a block of code that performs a specific task. In JavaScript, you can define and call functions like this:

function sayHello(name) {
    
    
    alert("Hello, " + name);
}

sayHello("Alice");
  1. Event handling
    JavaScript is often used to respond to user operations, such as clicks, keyboard input, etc.
<button onclick="sayHello()">点击这里</button>
  1. Manipulating HTML Elements
    JavaScript can be used to dynamically modify HTML content and styles.
document.getElementById("myElement").innerHTML = "新内容";
  1. Debugging
    In the browser, you can use console.log() to print debugging information.
console.log("这条信息将显示在控制台");
  1. External JavaScript files
    You can also place JavaScript code in an external file and then reference it in the HTML file.

Example: External JavaScript files

<script src="path/to/your/script.js"></script>

The above are some basic ways to use JavaScript. As your proficiency with JavaScript increases, you'll be able to use it to create more complex functionality and interactive web pages.

Guess you like

Origin blog.csdn.net/r081r096/article/details/135411419