当前位置:首页 > 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()方法:

js实现jquery

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操作方法:

js实现jquery

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。

标签: jsjquery
分享给朋友:

相关文章

vue.js实现轮播

vue.js实现轮播

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

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现验证码

js实现验证码

使用Canvas生成图形验证码 在HTML中创建一个Canvas元素用于绘制验证码。通过JavaScript随机生成数字或字母组合,并添加干扰线、噪点等干扰元素增强安全性。 <canvas i…

js实现文件下载

js实现文件下载

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

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

jquery教程

jquery教程

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