当前位置:首页 > JavaScript

js原生实现

2026-03-14 05:39:16JavaScript

原生JavaScript实现常见功能

事件监听

使用addEventListener绑定事件:

document.getElementById('myButton').addEventListener('click', function() {
  console.log('Button clicked');
});

AJAX请求

使用XMLHttpRequest对象:

js原生实现

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();

元素选择

通过选择器获取元素:

// 通过ID
const el = document.getElementById('elementId');

// 通过类名
const elements = document.getElementsByClassName('className');

// 通过标签名
const tags = document.getElementsByTagName('div');

// 通过CSS选择器
const firstMatch = document.querySelector('.container');
const allMatches = document.querySelectorAll('.item');

动态创建元素

const newDiv = document.createElement('div');
newDiv.className = 'box';
newDiv.textContent = 'New Element';
document.body.appendChild(newDiv);

类操作

const element = document.getElementById('myElement');

// 添加类
element.classList.add('new-class');

// 移除类
element.classList.remove('old-class');

// 切换类
element.classList.toggle('active');

数据存储

使用localStorage

js原生实现

// 存储数据
localStorage.setItem('key', 'value');

// 获取数据
const data = localStorage.getItem('key');

// 移除数据
localStorage.removeItem('key');

定时器

// 延时执行
setTimeout(function() {
  console.log('Executed after 1 second');
}, 1000);

// 循环执行
const intervalId = setInterval(function() {
  console.log('Executed every 1 second');
}, 1000);

// 清除定时器
clearInterval(intervalId);

表单处理

document.forms['myForm'].addEventListener('submit', function(e) {
  e.preventDefault();
  const formData = new FormData(this);
  const username = formData.get('username');
  console.log(username);
});

数组操作

常见原生数组方法:

const numbers = [1, 2, 3, 4];

// 遍历
numbers.forEach(function(item) {
  console.log(item);
});

// 映射
const doubled = numbers.map(function(item) {
  return item * 2;
});

// 过滤
const evens = numbers.filter(function(item) {
  return item % 2 === 0;
});

// 查找
const found = numbers.find(function(item) {
  return item > 2;
});

对象操作

const person = {
  name: 'John',
  age: 30
};

// 获取键
const keys = Object.keys(person);

// 获取值
const values = Object.values(person);

// 合并对象
const newPerson = Object.assign({}, person, { city: 'New York' });

字符串操作

const str = 'Hello World';

// 分割
const parts = str.split(' ');

// 替换
const newStr = str.replace('World', 'JavaScript');

// 包含检测
const hasHello = str.includes('Hello');

// 截取
const subStr = str.substring(0, 5);

日期处理

const now = new Date();

// 获取年份
const year = now.getFullYear();

// 获取月份 (0-11)
const month = now.getMonth();

// 获取日期
const day = now.getDate();

// 格式化日期
const formatted = `${year}-${month + 1}-${day}`;

动画实现

使用requestAnimationFrame

function animate() {
  const element = document.getElementById('animated');
  let position = 0;

  function step() {
    position += 1;
    element.style.left = position + 'px';
    if (position < 100) {
      requestAnimationFrame(step);
    }
  }

  requestAnimationFrame(step);
}

Promise实现

function fetchData(url) {
  return new Promise(function(resolve, reject) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onload = function() {
      if (xhr.status === 200) {
        resolve(xhr.response);
      } else {
        reject(new Error(xhr.statusText));
      }
    };
    xhr.onerror = function() {
      reject(new Error('Network Error'));
    };
    xhr.send();
  });
}

标签: js
分享给朋友:

相关文章

js 实现倒计时

js 实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。 使用 setInterval 实…

js 实现vue

js 实现vue

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

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

js实现点击显示和隐藏

js实现点击显示和隐藏

实现点击显示和隐藏的JavaScript方法 使用classList.toggle切换类名 通过添加/移除CSS类控制元素的显示与隐藏,需提前在CSS中定义隐藏样式(如display: none)。…

js钟表实现

js钟表实现

实现JavaScript钟表的基本方法 创建一个简单的JavaScript钟表可以通过以下步骤完成,涵盖数字和模拟两种形式。 数字钟表实现 HTML结构只需一个显示时间的容器: <div i…