当前位置:首页 > 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实现图片预览

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

js实现换肤

js实现换肤

使用CSS变量实现换肤 通过CSS变量可以轻松实现主题切换功能。CSS变量在根元素中定义,通过JavaScript动态修改这些变量值。 :root { --primary-color: #349…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(func,…

js实现图片

js实现图片

图片加载与显示 在JavaScript中,可以通过Image对象动态加载图片。创建实例后设置src属性触发加载,通过onload回调处理加载完成后的操作: const img = new Ima…

js图片轮播的实现

js图片轮播的实现

基础图片轮播实现 使用HTML、CSS和JavaScript实现一个简单的图片轮播效果。HTML部分定义轮播容器和图片,CSS负责样式和过渡效果,JavaScript处理逻辑。 <div cl…

js 实现文件上传

js 实现文件上传

文件上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。以下是一个基础示例: <input ty…