当前位置:首页 > JavaScript

js 实现 jq

2026-01-31 15:29:14JavaScript

实现 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,支持链式调用:

js 实现 jq

$('#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 和动画。可以根据需要进一步扩展功能。

标签: jsjq
分享给朋友:

相关文章

vue实现js休眠

vue实现js休眠

Vue 中实现 JavaScript 休眠 在 Vue 中实现 JavaScript 休眠通常需要使用异步方式,以避免阻塞主线程。以下是几种常见方法: 使用 setTimeout 和 Pro…

vue.js实现轮播

vue.js实现轮播

Vue.js 实现轮播功能 使用第三方库(推荐) Vue.js 生态中有许多成熟的轮播组件库,例如 vue-awesome-swiper 或 swiper,它们功能丰富且易于集成。 安装 swipe…

jq 实现 vue

jq 实现 vue

jq 实现 Vue 的核心思路 使用 jq(jQuery)实现类似 Vue 的数据绑定和响应式功能,可以通过以下方式模拟核心特性。虽然无法完全复现 Vue 的完整功能,但能实现基础的双向绑定和模板渲染…

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClipb…

js实现列表

js实现列表

使用 JavaScript 实现列表 JavaScript 提供了多种方式来实现列表功能,包括数组操作、DOM 元素动态生成等。以下是几种常见的实现方法: 使用数组存储列表数据 数组是 JavaSc…

js实现目录

js实现目录

实现目录的基本思路 在JavaScript中实现目录功能通常涉及以下几个核心步骤:解析文档中的标题元素(如h1-h6),动态生成目录结构,并添加交互逻辑(如点击跳转)。以下是具体实现方法: 解析标题…