当前位置:首页 > JavaScript

js实现jquery

2026-04-06 15:53:47JavaScript

使用原生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的一些实用方法:

js实现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。

标签: jsjquery
分享给朋友:

相关文章

jquery文档

jquery文档

以下是关于 jQuery 文档的核心资源和使用方法整理: jQuery 官方文档 jQuery 官方文档是学习和使用 jQuery 最权威的资源,包含详细的 API 说明、示例和更新日志。 官…

js实现文件下载

js实现文件下载

使用 a 标签下载文件 通过动态创建 a 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据的情况。 function downloadFile(url, f…

jquery教程

jquery教程

jQuery 教程:基础与实用方法 jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。其核心特点是“写得更少…

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js实现vr

js实现vr

使用WebXR API实现VR体验 WebXR是浏览器中实现VR和AR体验的标准API,它取代了早期的WebVR。现代浏览器如Chrome、Edge和Firefox已支持WebXR。 // 初始化W…

jquery选择器

jquery选择器

jQuery 选择器基础 jQuery 选择器用于选取 DOM 元素,基于 CSS 选择器语法扩展。通过 $() 或 jQuery() 函数调用,返回匹配元素的集合。 常见选择器类型…