js实现jquery
使用原生JavaScript实现jQuery功能
jQuery的核心功能包括DOM操作、事件处理、AJAX请求等。以下使用原生JavaScript实现类似功能:
DOM选择器
jQuery的$()选择器可以用document.querySelectorAll()替代:
function $(selector) {
return document.querySelectorAll(selector);
}
// 使用示例
$('.my-class').forEach(el => {
el.style.color = 'red';
});
事件处理
替代jQuery的.on()方法:
Element.prototype.on = function(event, callback) {
this.addEventListener(event, callback);
};
// 使用示例
$('#my-button')[0].on('click', () => {
console.log('Button clicked');
});
AJAX请求
实现简单的$.ajax():
window.ajax = function(options) {
const xhr = new XMLHttpRequest();
xhr.open(options.method || 'GET', options.url);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
options.success && options.success(xhr.response);
} else {
options.error && options.error(xhr.statusText);
}
};
xhr.onerror = function() {
options.error && options.error('Network error');
};
xhr.send(options.data);
};
// 使用示例
ajax({
url: '/api/data',
method: 'GET',
success: (data) => {
console.log('Received:', data);
},
error: (err) => {
console.error('Error:', err);
}
});
DOM操作
实现常见的DOM操作方法:
Element.prototype.html = function(content) {
if (content === undefined) {
return this.innerHTML;
}
this.innerHTML = content;
return this;
};
Element.prototype.addClass = function(className) {
this.classList.add(className);
return this;
};
Element.prototype.removeClass = function(className) {
this.classList.remove(className);
return this;
};
// 使用示例
$('#my-element')[0].html('<p>New content</p>').addClass('highlight');
链式调用
通过返回this实现jQuery的链式调用:
Element.prototype.css = function(property, value) {
if (value === undefined && typeof property === 'string') {
return getComputedStyle(this)[property];
}
if (typeof property === 'object') {
Object.entries(property).forEach(([prop, val]) => {
this.style[prop] = val;
});
} else {
this.style[property] = value;
}
return this;
};
// 使用示例
$('#my-element')[0]
.css('color', 'red')
.css({ backgroundColor: 'blue', fontSize: '20px' });
动画效果
实现简单的动画效果:
Element.prototype.animate = function(properties, duration, easing, callback) {
const startTime = performance.now();
const startValues = {};
Object.keys(properties).forEach(prop => {
startValues[prop] = parseFloat(getComputedStyle(this)[prop]);
});
const animateFrame = (time) => {
const elapsed = time - startTime;
const progress = Math.min(elapsed / duration, 1);
Object.entries(properties).forEach(([prop, endValue]) => {
const startValue = startValues[prop];
const currentValue = startValue + (endValue - startValue) * progress;
this.style[prop] = currentValue + (prop === 'opacity' ? '' : 'px');
});
if (progress < 1) {
requestAnimationFrame(animateFrame);
} else if (callback) {
callback();
}
};
requestAnimationFrame(animateFrame);
return this;
};
// 使用示例
$('#my-element')[0].animate(
{ opacity: 0.5, left: 100 },
1000,
'linear',
() => console.log('Animation complete')
);
实用工具方法
实现jQuery的一些实用方法:

// 检查文档是否加载完成
document.ready = function(callback) {
if (document.readyState !== 'loading') {
callback();
} else {
document.addEventListener('DOMContentLoaded', callback);
}
};
// 遍历元素
NodeList.prototype.each = function(callback) {
this.forEach((el, index) => callback.call(el, index, el));
return this;
};
// 使用示例
document.ready(() => {
$('.items').each((index, el) => {
console.log(`Item ${index}:`, el.textContent);
});
});
这些实现提供了jQuery核心功能的简化版本。实际项目中,如果需要更完整的功能,可以考虑使用轻量级替代库如Zepto.js,或者直接使用现代浏览器提供的原生API。






