// 选择元素
const $element = $('#myElement');
const $elements = $('.myClass');
// 修改内容
$element.text('新文本');
$element.html('<strong>HTML内容</strong>');
// 修改样式
$element.css('color', 'red');
$element.addClass('active');
$element.removeClass('inactive');
// 事件处理
$element.on('click', function() {
console.log('元素被点击');
});
// AJAX请求
$.ajax({
url: '/api/data',
method: 'GET',
success: function(data) {
console.log('数据获取成功', data);
},
error: function(error) {
console.error('请求失败', error);
}
});
// 选择元素
const element = document.getElementById('myElement');
const elements = document.querySelectorAll('.myClass');
// 事件委托
document.addEventListener('click', function(e) {
if (e.target.matches('.btn')) {
console.log('按钮被点击');
}
});
// 表单验证
function validateForm() {
const email = document.getElementById('email').value;
if (!email.includes('@')) {
alert('请输入有效的邮箱地址');
return false;
}
return true;
}
// 本地存储
localStorage.setItem('user', JSON.stringify({name: 'John'}));
const user = JSON.parse(localStorage.getItem('user'));
// 定时器
setTimeout(() => {
console.log('2秒后执行');
}, 2000);
setInterval(() => {
console.log('每隔1秒执行');
}, 1000);
// 箭头函数
const multiply = (a, b) => a * b;
// 模板字符串
const name = 'John';
console.log(`Hello, ${name}!`);
// 解构赋值
const { firstName, lastName } = user;
const [first, second] = array;
// Promise和async/await
async function fetchData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
return data;
} catch (error) {
console.error('获取数据失败', error);
}
}
// 数组方法
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
// 防抖函数
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
// 深度复制
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
// 格式化日期
function formatDate(date) {
return new Date(date).toLocaleDateString('zh-CN');
}
// 生成随机ID
function generateId() {
return Math.random().toString(36).substr(2, 9);
}