Tairraos 发表于 2020-1-2 20:44

[Javascript] 用原生JS实现jQuery的功能

本帖最后由 Tairraos 于 2020-10-25 15:51 编辑

帖子很长,收藏下来必然某天用得到。
喜欢请点击下方免费评分,谢谢
======================
还有几帖你一定会喜欢的:
Python资源大全:https://www.52pojie.cn/thread-1081229-1-1.html
Python tkinter UI指南 https://www.52pojie.cn/thread-1290751-1-1.html
原生 Javascript 实现 jQuery 的功能: https://www.52pojie.cn/thread-1084552-1-1.html
Chrome调试器Console的进阶用法 https://www.52pojie.cn/thread-1156239-1-1.html
Javascript 极限省字节(看懂混淆后的代码) https://www.52pojie.cn/thread-1056860-1-1.html
写JS必备,ESLINT配置说明 https://www.52pojie.cn/thread-1290700-1-1.html
======================
### 说明

IE9为2011年发布,以下注明IE8, 9的仅表示IE的兼容程度
以下代码 Chrome/FF/Safari/Edge 2010年后的各版本都能使用

### AJAX

#### 替代框架: (https://github.com/ded/Reqwest) (https://github.com/then/request) (https://github.com/visionmedia/superagent)

### JSON


#### JQUERY
```javascript
$.getJSON('/my/url', function(data) {

});
```

#### IE9+
```javascript
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
if (request.status >= 200 && request.status < 400) {
    // Success!
    var data = JSON.parse(request.responseText);
} else {
    // We reached our target server, but it returned an error

}
};

request.onerror = function() {
// There was a connection error of some sort
};

request.send();
```

### Post


#### JQUERY
```javascript
$.ajax({
type: 'POST',
url: '/my/url',
data: data
});
```

#### IE8+
```javascript
var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
```

### Request


#### JQUERY
```javascript
$.ajax({
type: 'GET',
url: '/my/url',
success: function(resp) {

},
error: function() {

}
});
```

#### IE9+
```javascript
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
if (request.status >= 200 && request.status < 400) {
    // Success!
    var resp = request.responseText;
} else {
    // We reached our target server, but it returned an error

}
};

request.onerror = function() {
// There was a connection error of some sort
};

request.send();
```

### EFFECTS

#### 替代框架: (http://daneden.github.io/animate.css/) (https://github.com/visionmedia/move.js)

### Fade In

#### JQUERY
```javascript
$(el).fadeIn();
```

#### IE9+
```javascript
function fadeIn(el) {
el.style.opacity = 0;

var last = +new Date();
var tick = function() {
    el.style.opacity = +el.style.opacity + (new Date() - last) / 400;
    last = +new Date();

    if (+el.style.opacity < 1) {
      (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
    }
};

tick();
}

fadeIn(el);
```

### Hide


#### JQUERY
```javascript
$(el).hide();
```

#### IE8+
```javascript
el.style.display = 'none';
```

### Show


#### JQUERY
```javascript
$(el).show();
```

#### IE8+
```javascript
el.style.display = '';
```

### ELEMENTS

#### 替代框架: (https://github.com/ded/bonzo) [$dom](https://github.com/julienw/dollardom)

### Add Class


#### JQUERY
```javascript
$(el).addClass(className);
```

#### IE8+
```javascript
if (el.classList)
el.classList.add(className);
else
el.className += ' ' + className;
```

### After


#### JQUERY
```javascript
$(el).after(htmlString);
```

#### IE8+
```javascript
el.insertAdjacentHTML('afterend', htmlString);
```

### Append


#### JQUERY
```javascript
$(parent).append(el);
```

#### IE8+
```javascript
parent.appendChild(el);
```

### Before


#### JQUERY
```javascript
$(el).before(htmlString);
```

#### IE8+
```javascript
el.insertAdjacentHTML('beforebegin', htmlString);
```

### Children


#### JQUERY
```javascript
$(el).children();
```

#### IE9+
```javascript
el.children
```

### Clone


#### JQUERY
```javascript
$(el).clone();
```

#### IE8+
```javascript
el.cloneNode(true);
```

### Contains


#### JQUERY
```javascript
$.contains(el, child);
```

#### IE8+
```javascript
el !== child && el.contains(child);
```

### Contains Selector


#### JQUERY
```javascript
$(el).find(selector).length;
```

#### IE8+
```javascript
el.querySelector(selector) !== null
```

### Each


#### JQUERY
```javascript
$(selector).each(function(i, el){

});
```

#### IE9+
```javascript
var elements = document.querySelectorAll(selector);
Array.prototype.forEach.call(elements, function(el, i){

});
```

### Empty


#### JQUERY
```javascript
$(el).empty();
```

#### IE9+
```javascript
el.innerHTML = '';
```

### Filter


#### JQUERY
```javascript
$(selector).filter(filterFn);
```

#### IE9+
```javascript
Array.prototype.filter.call(document.querySelectorAll(selector), filterFn);
```

### Find Children


#### JQUERY
```javascript
$(el).find(selector);
```

#### IE8+
```javascript
el.querySelectorAll(selector);
```

### Find Elements


#### 替代框架: (https://github.com/ded/qwery) (http://sizzlejs.com/)

#### JQUERY
```javascript
$('.my
# awesome selector');
```

#### IE8+
```javascript
document.querySelectorAll('.my
# awesome selector');
```

### Get Attributes


#### JQUERY
```javascript
$(el).attr('tabindex');
```

#### IE8+
```javascript
el.getAttribute('tabindex');
```

### Get Html


#### JQUERY
```javascript
$(el).html();
```

#### IE8+
```javascript
el.innerHTML
```

### Get Outer Html


#### JQUERY
```javascript
$('<div>').append($(el).clone()).html();
```

#### IE8+
```javascript
el.outerHTML
```

### Get Style


#### JQUERY
```javascript
$(el).css(ruleName);
```

#### IE9+
```javascript
getComputedStyle(el);
```

### Get Text


#### JQUERY
```javascript
$(el).text();
```

#### IE9+
```javascript
el.textContent
```

### Has Class


#### JQUERY
```javascript
$(el).hasClass(className);
```

#### IE8+
```javascript
if (el.classList)
el.classList.contains(className);
else
new RegExp('(^| )' + className + '(|$)', 'gi').test(el.className);
```

### Matches


#### JQUERY
```javascript
$(el).is($(otherEl));
```

#### IE8+
```javascript
el === otherEl
```

### Matches Selector


#### JQUERY
```javascript
$(el).is('.my-class');
```

#### IE9+
```javascript
var matches = function(el, selector) {
return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector);
};

matches(el, '.my-class');
```

### Next


#### JQUERY
```javascript
$(el).next();
```

#### IE9+
```javascript
el.nextElementSibling
```

### Offset


#### JQUERY
```javascript
$(el).offset();
```

#### IE8+
```javascript
var rect = el.getBoundingClientRect();

{
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
}
```

### Offset Parent


#### JQUERY
```javascript
$(el).offsetParent();
```

#### IE8+
```javascript
el.offsetParent || el
```

### Outer Height


#### JQUERY
```javascript
$(el).outerHeight();
```

#### IE8+
```javascript
el.offsetHeight
```

### Outer Height With Margin


#### JQUERY
```javascript
$(el).outerHeight(true);
```

#### IE9+
```javascript
function outerHeight(el) {
var height = el.offsetHeight;
var style = getComputedStyle(el);

height += parseInt(style.marginTop) + parseInt(style.marginBottom);
return height;
}

outerHeight(el);
```

### Outer Width


#### JQUERY
```javascript
$(el).outerWidth();
```

#### IE8+
```javascript
el.offsetWidth
```

### Outer Width With Margin


#### JQUERY
```javascript
$(el).outerWidth(true);
```

#### IE9+
```javascript
function outerWidth(el) {
var width = el.offsetWidth;
var style = getComputedStyle(el);

width += parseInt(style.marginLeft) + parseInt(style.marginRight);
return width;
}

outerWidth(el);
```

### Parent


#### JQUERY
```javascript
$(el).parent();
```

#### IE8+
```javascript
el.parentNode
```

### Position


#### JQUERY
```javascript
$(el).position();
```

#### IE8+
```javascript
{left: el.offsetLeft, top: el.offsetTop}
```

### Position Relative To Viewport


#### JQUERY
```javascript
var offset = el.offset();

{
top: offset.top - document.body.scrollTop,
left: offset.left - document.body.scrollLeft
}
```

#### IE8+
```javascript
el.getBoundingClientRect()
```

### Prepend


#### JQUERY
```javascript
$(parent).prepend(el);
```

#### IE8+
```javascript
parent.insertBefore(el, parent.firstChild);
```

### Prev


#### JQUERY
```javascript
$(el).prev();
```

#### IE9+
```javascript
el.previousElementSibling
```

### Remove


#### JQUERY
```javascript
$(el).remove();
```

#### IE8+
```javascript
el.parentNode.removeChild(el);
```

### Remove Class


#### JQUERY
```javascript
$(el).removeClass(className);
```

#### IE8+
```javascript
if (el.classList)
el.classList.remove(className);
else
el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
```

### Replace From Html


#### JQUERY
```javascript
$(el).replaceWith(string);
```

#### IE8+
```javascript
el.outerHTML = string;
```

### Set Attributes


#### JQUERY
```javascript
$(el).attr('tabindex', 3);
```

#### IE8+
```javascript
el.setAttribute('tabindex', 3);
```

### Set Html


#### JQUERY
```javascript
$(el).html(string);
```

#### IE8+
```javascript
el.innerHTML = string;
```

### Set Style


#### JQUERY
```javascript
$(el).css('border-width', '20px');
```

#### IE8+
```javascript
// Use a class if possible
el.style.borderWidth = '20px';
```

### Set Text


#### JQUERY
```javascript
$(el).text(string);
```

#### IE9+
```javascript
el.textContent = string;
```

### Siblings


#### JQUERY
```javascript
$(el).siblings();
```

#### IE9+
```javascript
Array.prototype.filter.call(el.parentNode.children, function(child){
return child !== el;
});
```

### Toggle Class


#### JQUERY
```javascript
$(el).toggleClass(className);
```

#### IE9+
```javascript
if (el.classList) {
el.classList.toggle(className);
} else {
var classes = el.className.split(' ');
var existingIndex = classes.indexOf(className);

if (existingIndex >= 0)
    classes.splice(existingIndex, 1);
else
    classes.push(className);

el.className = classes.join(' ');
}
```

### EVENTS

### Off


#### JQUERY
```javascript
$(el).off(eventName, eventHandler);
```

#### IE9+
```javascript
el.removeEventListener(eventName, eventHandler);
```

### On


#### JQUERY
```javascript
$(el).on(eventName, eventHandler);
```

#### IE9+
```javascript
el.addEventListener(eventName, eventHandler);
```

### Ready


#### JQUERY
```javascript
$(document).ready(function(){

});
```

#### IE9+
```javascript
function ready(fn) {
if (document.readyState != 'loading'){
    fn();
} else {
    document.addEventListener('DOMContentLoaded', fn);
}
}
```

### Trigger Custom


#### 替代框架: (https://github.com/Wolfy87/EventEmitter) (https://github.com/arextar/Vine) (https://github.com/jeromeetienne/microevent.js)

#### JQUERY
```javascript
$(el).trigger('my-event', {some: 'data'});
```

#### IE9+
```javascript
if (window.CustomEvent) {
var event = new CustomEvent('my-event', {detail: {some: 'data'}});
} else {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('my-event', true, true, {some: 'data'});
}

el.dispatchEvent(event);
```

### Trigger Native


#### JQUERY
```javascript
$(el).trigger('change');
```

#### IE9+
```javascript
// For a full list of event types: https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent
var event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
el.dispatchEvent(event);
```

### UTILS

### Bind


#### JQUERY
```javascript
$.proxy(fn, context);
```

#### IE9+
```javascript
fn.bind(context);
```

### Array Each


#### JQUERY
```javascript
$.each(array, function(i, item){

});
```

#### IE9+
```javascript
array.forEach(function(item, i){

});
```

### Deep Extend


#### JQUERY
```javascript
$.extend(true, {}, objA, objB);
```

#### IE8+
```javascript
var deepExtend = function(out) {
out = out || {};

for (var i = 1; i < arguments.length; i++) {
    var obj = arguments;

    if (!obj)
      continue;

    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
      if (typeof obj === 'object')
          out = deepExtend(out, obj);
      else
          out = obj;
      }
    }
}

return out;
};

deepExtend({}, objA, objB);
```

### Extend


#### 替代框架: (http://lodash.com/docs#assign) (http://underscorejs.org/#extend) (http://www.2ality.com/2014/01/object-assign.html)

#### JQUERY
```javascript
$.extend({}, objA, objB);
```

#### IE8+
```javascript
var extend = function(out) {
out = out || {};

for (var i = 1; i < arguments.length; i++) {
    if (!arguments)
      continue;

    for (var key in arguments) {
      if (arguments.hasOwnProperty(key))
      out = arguments;
    }
}

return out;
};

extend({}, objA, objB);
```

### Index Of


#### JQUERY
```javascript
$.inArray(item, array);
```

#### IE9+
```javascript
array.indexOf(item);
```

### Is Array


#### JQUERY
```javascript
$.isArray(arr);
```

#### IE9+
```javascriptA
Array.isArray(arr);
```

### Map


#### JQUERY
```javascript
$.map(array, function(value, index){

});
```

#### IE9+
```javascript
array.map(function(value, index){

});
```

### Now


#### JQUERY
```javascript
$.now();
```

#### IE9+
```javascript
Date.now();
```

### Parse Html


#### JQUERY
```javascript
$.parseHTML(htmlString);
```

#### IE9+
```javascript
var parseHTML = function(str) {
var tmp = document.implementation.createHTMLDocument();
tmp.body.innerHTML = str;
return tmp.body.children;
};

parseHTML(htmlString);
```

### Parse Json


#### JQUERY
```javascript
$.parseJSON(string);
```

#### IE8+
```javascript
JSON.parse(string);
```

### Trim


#### JQUERY
```javascript
$.trim(string);
```

#### IE9+
```javascript
string.trim();
```

### Type


#### JQUERY
```javascript
$.type(obj);
```

#### IE8+
```javascript
Object.prototype.toString.call(obj).replace(/^\$/, '$1').toLowerCase();
```





喜欢请点击下方免费评分,谢谢
======================
还有几帖你一定会喜欢的:
Python资源大全:https://www.52pojie.cn/thread-1081229-1-1.html
Python tkinter UI指南 https://www.52pojie.cn/thread-1290751-1-1.html
原生 Javascript 实现 jQuery 的功能: https://www.52pojie.cn/thread-1084552-1-1.html
Chrome调试器Console的进阶用法 https://www.52pojie.cn/thread-1156239-1-1.html
Javascript 极限省字节(看懂混淆后的代码) https://www.52pojie.cn/thread-1056860-1-1.html
写JS必备,ESLINT配置说明 https://www.52pojie.cn/thread-1290700-1-1.html
======================

sunil 发表于 2020-1-2 23:55

说服我为什么不用jQuery?
这比jQuery要好?

Tairraos 发表于 2020-1-8 16:27

changjiang 发表于 2020-1-7 13:26
想问下,js如何像jquery那样根据文本选择元素呢?比如jquery写的是$("*:contains(is)"),那么对应的js代码 ...

jquery依赖了一个名叫sizzle的包(同一开发者), 选择器是sizzle 实现的。

看sizzle源代码就行
https://github.com/jquery/sizzle/blob/master/src/sizzle.js

contains是硬实现的,不是原生js方法的简单封装。但是jquery和sizzle的大部分工具和方法都是用浏览器原生方法实现的。

被封号的萌新 发表于 2020-1-2 22:52

a13381041 发表于 2020-1-3 10:29

很六啊,很有参考意义,收藏了

Tairraos 发表于 2020-1-6 08:37

被封号的萌新 发表于 2020-1-2 22:52
刚接触js,才学到千峰的JavaScript教程。请问楼主有好的教程么,一直用易语言写post脚本太麻烦了。就差js来 ...

你有其它语言基础,看<<JS精粹>>,基本就是讲JS和其它语言不一样的那些地方。
再找一个喜欢用的JS工具框(比如jquery, lodash, dash, zepto)架来读一下源代码,把读代码时心中产生的问题都解决了,就能确保高水平习得了

Tairraos 发表于 2020-1-6 08:44

sunil 发表于 2020-1-2 23:55
说服我为什么不用jQuery?
这比jQuery要好?

1 上文不是说要让你放弃jQuery,而是让你有点备胎技能

2 如果你永远只是自己给自己写代码,或者你的开发不在乎交付时的尺寸,不在乎那可以一直使用你喜欢的工具没问题。

被封号的萌新 发表于 2020-1-6 11:53

Tairraos 发表于 2020-1-6 23:54

被封号的萌新 发表于 2020-1-6 11:53
谢谢老师。好的

天~ 不要叫我老师。我还没达到能教学的程度。就是随意说一下自己的意见,共同进步吧。

changjiang 发表于 2020-1-7 13:26

想问下,js如何像jquery那样根据文本选择元素呢?比如jquery写的是$("*:contains(is)"),那么对应的js代码是什么?
页: [1] 2
查看完整版本: [Javascript] 用原生JS实现jQuery的功能