当前位置:首页 > jquery

jquery转js

2026-02-03 22:09:51jquery

使用原生JavaScript替代jQuery选择器

jQuery的选择器功能可以通过document.querySelectordocument.querySelectorAll实现。

  • 单元素选择
    // jQuery: $('#id')
    document.getElementById('id'); // 或 document.querySelector('#id');
  • 多元素选择
    // jQuery: $('.class')
    document.querySelectorAll('.class');

DOM操作替代

jQuery的DOM操作方法可以用原生JavaScript属性或方法替换。

  • 修改内容
    // jQuery: $('#el').text('content')
    document.getElementById('el').textContent = 'content';
  • 修改HTML
    // jQuery: $('#el').html('<span>content</span>')
    document.getElementById('el').innerHTML = '<span>content</span>';
  • 修改属性
    // jQuery: $('#el').attr('src', 'image.jpg')
    document.getElementById('el').setAttribute('src', 'image.jpg');

事件监听替代

jQuery的事件绑定可以用addEventListener替代。

jquery转js

// jQuery: $('#el').on('click', handler)
document.getElementById('el').addEventListener('click', handler);

AJAX请求替代

使用fetchXMLHttpRequest替代jQuery的$.ajax

  • 使用fetch
    // jQuery: $.ajax({ url, method: 'GET' })
    fetch(url)
      .then(response => response.json())
      .then(data => console.log(data));
  • 使用XMLHttpRequest
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onload = () => console.log(xhr.responseText);
    xhr.send();

类名操作替代

jQuery的addClassremoveClass等可以用classList替代。

jquery转js

// jQuery: $('#el').addClass('active')
document.getElementById('el').classList.add('active');

动画效果替代

CSS动画或requestAnimationFrame可以替代jQuery动画。

  • CSS过渡
    .element { transition: opacity 0.3s; }
    // jQuery: $('#el').fadeIn()
    document.getElementById('el').style.opacity = '1';

遍历与数组操作

jQuery的$.each可以用forEachfor...of替代。

// jQuery: $.each(array, (i, item) => {})
array.forEach((item, i) => {});

链式操作替代

原生JavaScript不支持链式操作,但可以通过变量暂存实现类似效果。

const el = document.getElementById('el');
el.style.color = 'red';
el.classList.add('highlight');

标签: jqueryjs
分享给朋友:

相关文章

jquery下载

jquery下载

jQuery下载方法 官方下载渠道 访问jQuery官网(https://jquery.com/),点击页面中的“Download”按钮。提供两个版本选择: Production版本:压缩后的…

jquery.js

jquery.js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,用于简化 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它的设计宗旨是“Write Less, Do Mor…

vue实现js休眠

vue实现js休眠

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

js实现拖拽

js实现拖拽

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

js实现全选

js实现全选

实现全选功能的方法 在JavaScript中实现全选功能通常涉及监听全选复选框的点击事件,并根据其状态控制其他复选框的选中状态。以下是几种常见的实现方式: 基础DOM操作实现 通过获取所有目标复选框…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('imag…