js实现的功能实现
实现动态表单验证
使用JavaScript实现表单验证功能,可以通过监听表单提交事件或输入框变化事件来验证用户输入。HTML5内置了基础验证属性(如required、pattern),但自定义验证逻辑需通过JavaScript完成。
document.getElementById('myForm').addEventListener('submit', function(event) {
const email = document.getElementById('email').value;
if (!email.includes('@')) {
event.preventDefault();
alert('请输入有效的邮箱地址');
}
});
数据过滤与搜索
通过数组方法(如filter、includes)实现前端数据搜索功能。适用于静态数据或API返回数据的实时筛选。
const data = ['Apple', 'Banana', 'Cherry'];
const searchTerm = 'a';
const results = data.filter(item =>
item.toLowerCase().includes(searchTerm.toLowerCase())
);
console.log(results); // ['Apple', 'Banana']
本地存储操作
利用localStorage或sessionStorage实现客户端数据持久化,适合保存用户偏好或临时数据。
// 存储数据
localStorage.setItem('theme', 'dark');
// 读取数据
const theme = localStorage.getItem('theme');
console.log(theme); // 'dark'
异步数据请求
使用fetch或axios从服务器获取数据,处理异步响应并更新DOM。

fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
document.getElementById('output').textContent = data.message;
})
.catch(error => console.error('Error:', error));
动态DOM操作
通过JavaScript创建、修改或删除页面元素,实现动态内容加载。
const newElement = document.createElement('div');
newElement.textContent = '动态添加的内容';
document.body.appendChild(newElement);
事件委托优化
利用事件冒泡机制,通过父元素监听子元素事件,减少事件监听器数量。

document.getElementById('list').addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
console.log('点击的项目:', event.target.textContent);
}
});
定时器与动画
使用setInterval或requestAnimationFrame实现简单动画效果。
let position = 0;
function animate() {
position += 1;
document.getElementById('box').style.left = position + 'px';
if (position < 100) {
requestAnimationFrame(animate);
}
}
animate();
模块化开发
通过ES6模块化组织代码,提高可维护性。
// math.js
export function add(a, b) { return a + b; }
// main.js
import { add } from './math.js';
console.log(add(2, 3)); // 5
性能优化技巧
使用防抖(debounce)或节流(throttle)限制高频事件触发频率。
function debounce(func, delay) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, arguments), delay);
};
}
window.addEventListener('resize', debounce(() => {
console.log('窗口大小改变');
}, 300));






