jQuery常用工具方法
0
0
2026年7月13日
图片懒加载
class LazyLoad {
constructor() {
this.images = document.querySelectorAll('img[data-src]');
this.observer = null;
this.init();
}
init() {
if ('IntersectionObserver' in window) {
this.observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.loadImage(entry.target);
this.observer.unobserve(entry.target);
}
});
});
this.images.forEach(img => this.observer.observe(img));
} else {
this.images.forEach(img => this.loadImage(img));
}
}
loadImage(img) {
img.src = img.dataset.src;
img.classList.add('loaded');
}
}
防抖节流详细实现
// 防抖
function debounce(fn, wait = 300, immediate = false) {
let timer = null;
let result;
const debounced = function(...args) {
if (timer) clearTimeout(timer);
if (immediate) {
const callNow = !timer;
timer = setTimeout(() => {
timer = null;
}, wait);
if (callNow) result = fn.apply(this, args);
} else {
timer = setTimeout(() => {
fn.apply(this, args);
}, wait);
}
return result;
};
debounced.cancel = function() {
clearTimeout(timer);
timer = null;
};
return debounced;
}
// 节流
function throttle(fn, wait = 300) {
let previous = 0;
return function(...args) {
const now = Date.now();
if (now - previous >= wait) {
previous = now;
fn.apply(this, args);
}
};
}
HTML5语义化标签
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>语义化页面</title>
</head>
<body>
<header>
<nav>
<h1>网站标题</h1>
<ul>
<li><a href="/">首页</a></li>
<li><a href="/about">关于</a></li>
</ul>
</nav>
</header>
<main>
<article>
<h2>文章标题</h2>
<p>文章内容...</p>
<figure>
<img src="image.jpg" alt="图片">
<figcaption>图片说明</figcaption>
</figure>
</article>
<aside>
<h3>侧边栏</h3>
</aside>
</main>
<footer>
<p>© 2024 版权所有</p>
</footer>
</body>
</html>
AJAX封装
class HttpClient {
constructor(baseURL = '') {
this.baseURL = baseURL;
}
async request(url, options = {}) {
const response = await fetch(this.baseURL + url, {
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
return response.json();
}
get(url, params = {}) {
const query = new URLSearchParams(params).toString();
return this.request(url + (query ? '?' + query : ''));
}
post(url, data = {}) {
return this.request(url, {
method: 'POST',
body: JSON.stringify(data)
});
}
}
jQuery工具包
$(function() {
$('#btn').click(function() { alert('点击了!'); });
$('.btn').addClass('active');
$('input[name="email"]').val('test@example.com');
$('#title').text('新标题');
$('#content').html('<strong>加粗文字</strong>');
$('#box').addClass('highlight');
$('#box').toggleClass('active');
$('#box').css({
'color': 'red',
'font-size': '16px'
});
$(document).on('click', '.dynamic-btn', function() {
console.log('动态按钮点击');
});
$.getJSON('/api/data', function(data) {
console.log(data);
});
$('#box').fadeIn(300);
$('#box').slideToggle(300);
});
工具函数
const utils = {
debounce(fn, delay = 300) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
},
throttle(fn, delay = 300) {
let last = 0;
return function(...args) {
const now = Date.now();
if (now - last >= delay) {
last = now;
fn.apply(this, args);
}
};
},
deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
},
formatDate(date, format = 'YYYY-MM-DD') {
const d = new Date(date);
return format
.replace('YYYY', d.getFullYear())
.replace('MM', String(d.getMonth() + 1).padStart(2, '0'))
.replace('DD', String(d.getDate()).padStart(2, '0'));
}
};
表单验证
class FormValidator {
constructor(formId) {
this.form = document.getElementById(formId);
this.rules = {};
this.errors = {};
}
addRule(field, rules) {
this.rules[field] = rules;
}
validate() {
this.errors = {};
for (let field in this.rules) {
const value = this.form[field].value;
for (let rule of this.rules[field]) {
if (!this.checkRule(value, rule)) {
this.errors[field] = rule.message;
break;
}
}
}
return Object.keys(this.errors).length === 0;
}
checkRule(value, rule) {
switch (rule.type) {
case 'required':
return value.trim() !== '';
case 'email':
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
case 'minLength':
return value.length >= rule.min;
default:
return true;
}
}
}
技术分享,欢迎评论区交流讨论。
在线咨询
上一个应该是我,我买了一年,实在没价值,...