CSS 弹性盒子深入理解
概述
JavaScript 是 Web 开发的核心语言,运行在浏览器中,为网页添加交互能力。
基本语法
// 变量声明
let name = '张三';
const age = 25;
var legacy = '旧方式';
// 输出
console.log('姓名:', name);
alert('你好!');
document.write('<h1>Hello World</h1>');
数据类型
// 原始类型
let str = '字符串'; // string
let num = 123; // number
let bool = true; // boolean
let nothing = null; // null
let notDefined; // undefined
// 引用类型
let arr = [1, 2, 3]; // array
let obj = { name: '王五' }; // object
// 类型检查
console.log(typeof str); // "string"
console.log(Array.isArray(arr)); // true
函数
// 函数声明
function greet(name) {
return '你好,' + name;
}
// 箭头函数
const add = (a, b) => a + b;
// 回调函数
setTimeout(() => {
console.log('3秒后执行');
}, 3000);
DOM 操作
// 获取元素
const el = document.getElementById('app');
const els = document.querySelectorAll('.item');
// 修改内容
el.textContent = '新文本';
el.innerHTML = '<strong>加粗</strong>';
// 事件监听
el.addEventListener('click', function(e) {
console.log('点击了', e.target);
});
总结
JavaScript 是前端开发的基础,掌握基本语法和 DOM 操作就能开始交互式网页开发。