js 实现 jq
实现 jQuery 核心功能
jQuery 是一个流行的 JavaScript 库,简化了 DOM 操作、事件处理和 Ajax 请求。以下是一个简化版的 jQuery 实现,涵盖核心功能。
选择器功能
function $(selector) {
if (selector.startsWith('<')) {
// 创建元素
const tagName = selector.replace(/[<>]/g, '')
return document.createElement(tagName)
} else {
// 选择元素
const elements = document.querySelectorAll(selector)
return elements.length === 1 ? elements[0] : Array.from(elements)
}
}
DOM 操作方法
$.fn = {
html: function(content) {
if (content === undefined) {
return this.innerHTML
}
this.innerHTML = content
return this
},
text: function(content) {
if (content === undefined) {
return this.textContent
}
this.textContent = content
return this
},
attr: function(name, value) {
if (value === undefined) {
return this.getAttribute(name)
}
this.setAttribute(name, value)
return this
}
}
// 将方法附加到选择结果上
function $(selector) {
const elements = document.querySelectorAll(selector)
const result = elements.length === 1 ? elements[0] : Array.from(elements)
Object.keys($.fn).forEach(method => {
if (result[method]) return
if (Array.isArray(result)) {
result[method] = function(...args) {
return result.map(el => $.fn[method].apply(el, args))
}
} else {
result[method] = function(...args) {
return $.fn[method].apply(result, args)
}
}
})
return result
}
事件处理
$.fn.on = function(eventName, handler) {
this.addEventListener(eventName, handler)
return this
}
$.fn.off = function(eventName, handler) {
this.removeEventListener(eventName, handler)
return this
}
Ajax 功能
$.ajax = function(options) {
const xhr = new XMLHttpRequest()
xhr.open(options.method || 'GET', options.url, true)
if (options.headers) {
Object.keys(options.headers).forEach(key => {
xhr.setRequestHeader(key, options.headers[key])
})
}
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(xhr.statusText)
}
xhr.send(options.data)
}
链式调用支持
所有方法都返回 this,支持链式调用:
$('#myElement')
.html('Hello')
.attr('data-test', 'value')
.on('click', () => console.log('Clicked'))
动画基础实现
$.fn.animate = function(properties, duration, callback) {
const element = this
const startTime = performance.now()
const startValues = {}
Object.keys(properties).forEach(prop => {
startValues[prop] = parseFloat(getComputedStyle(element)[prop])
})
function step(currentTime) {
const elapsed = currentTime - startTime
const progress = Math.min(elapsed / duration, 1)
Object.keys(properties).forEach(prop => {
const start = startValues[prop]
const end = parseFloat(properties[prop])
const current = start + (end - start) * progress
element.style[prop] = current + (prop === 'opacity' ? '' : 'px')
})
if (progress < 1) {
requestAnimationFrame(step)
} else if (callback) {
callback()
}
}
requestAnimationFrame(step)
return this
}
使用方法示例
// 选择元素
const elements = $('.my-class')
// 修改内容
$('#myId').html('<p>New content</p>')
// 添加事件
$('#btn').on('click', () => alert('Clicked!'))
// Ajax 请求
$.ajax({
url: '/api/data',
method: 'GET',
success: data => console.log(data),
error: err => console.error(err)
})
// 动画效果
$('.box').animate({
left: '100px',
opacity: 0.5
}, 1000)
这个实现包含了 jQuery 的核心功能,包括选择器、DOM 操作、事件处理、Ajax 和动画。可以根据需要进一步扩展功能。







