With the improvement of JavaScript itself, more and more people are beginning to like to use native JavaScript development instead of various libraries, and many of them have made voices of using native JavaScript instead of jQuery. That's not a bad thing, but it's not necessarily a good thing either. If you really want to remove jQuery from your front-end dependency library, I suggest you think carefully.
First of all, jQuery is a third-party library. One of the values of libraries is that they greatly simplify development. Generally, third-party libraries are implemented by native language features and basic API libraries. Therefore, in theory, any third-party library can be replaced with native language features. The question is whether it is worth it?
The role of jQueryQuote from the jQuery official website:jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML documentThis paragraph is a very humble introduction to jQuery's contribution to DOM processing and cross-browser processing. In fact, this is the main reason why we choose jQuery, and use some of the tools it brings, such as array tools, Deferred, etc. For me, the most commonly used functions includetraversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
- Querying in the DOM tree
- Modifying the DOM tree and DOM related operations
- Event handling
- Ajax
- Deferred and Promise
- Object and array processing
- There is another thing that I have been using but it is difficult to think of when making a list-cross-browser
querySelectorAll() was used instead of
$(), I couldn’t help but wonder why I had to write ten when jQuery can solve it with just one character. Six characters? Most browsers implement
$(), but when writing native code, do you consider the browser compatibility of
$()? jQuery has been considered!
// 创建一个 ul 列表并加在 #container 中 $("
- ").append(
$("
- ").append(
$("").attr("href", "#").text("first")),
$("
- ").append( $("").attr("href", "#").text("second")), $("
- ").append( $("").attr("href", "#").text("third")) ).appendTo($("#container"));There is no problem in implementing this code using
document.createElement()
, but the amount of code is much larger, and there will be a lot of duplication (or similar) code. Of course, it is possible to extract these repeated codes and write them into functions... but jQuery has already done it.
Note, the method of spelling HTML is really weak, it is error-prone and difficult to read. If you have ES6 string templates, it’s also a good idea to use them to write HTML.
As far as DOM manipulation is concerned, jQuery is still a very useful tool. This is jQuery's replacement for native JavaScript, as it was and still is. The decline of jQuery tool functionsWhen jQuery was invented in 2006, there was no ES5 (released in June 2011). Even long after ES5 was released, not all browsers supported it. Therefore, during this period, in addition to DOM operations, jQuery's great contribution was to solve cross-browser problems and provide convenient object and array manipulation tools, such aseach()
Now ECMAScript has just released the 2017 standard, and the problem of confusing browser standards has been well solved. Translation tools like Babel and new languages like TypeScript have also appeared in the front-end world. So now everyone can use various new language features with confidence, even if the relevant standards for ECMAScript are still being formulated. During this period, a large number of tool methods provided by jQuery already had native alternatives - when there is not much difference in usage, it is indeed better to use native implementations. In fact, jQuery is also using native implementation as much as possible to improve execution efficiency. jQuery has not given up on these natively implemented tool functions/methods, mainly because of backward compatibility and continued browser compatibility - after all, not every developer who uses jQuery will use translation tools. So, for JavaScript developers, jQuery does have many tool methods that can be replaced by native JavaScript functions/methods. For example,,
index( )and
filteretc.
$.parseJSON()
can be replaced by
JSON.parse(), and
JSON.stringify()It also makes up for the shortcomings of jQuery
not having $.toJSON();
$.extend()
的部分功能可以由Object.assign()
替代`$.fn
的一些数据处理工具方法,比如each()
、index()
等都可以用Array.prototype
中相应的工具方法替代,比如forEach()
、indexOf()
等。$.Deferred()
和 jQuery Promise 在某些情况下可以用原生 Promise 替代。它们在没有 ES6 之前也算是个不错的 Promise 实现。......
$.fn
就是jQuery.prototype
,也就是 jQuery 对象的原型。所以在其上定义的方法就是 jQuery 对象的方法。这些工具方法在原生 JavaScript 中已经逐渐补充完善,但它们仍然只是在某些情况下可以被替代……因为 jQuery 对象是一个特有的数据结构,针对 jQuery 自身创建的工具方法在作用于 jQuery 对象的时候会有一些针对性的实现——既然 DOM 操作仍然不能把 jQuery 抛开,那这些方法也就不可能被完全替换掉。
jQuery 与原生 JavaScript 的结合
有时候需要用 jQuery,有时候不需要用,该如何分辨?
jQuery 的优势在于它的 DOM 处理、Ajax,以及跨浏览器。如果在项目中引入 jQuery,多半是因为对这些功能的需求。而对于不操作 DOM,也不需要考虑跨浏览器(比如用于转译工具)的部分,则考虑尽可能的用原生 JavaScript 实现。
如此以来,一定会存在 jQuery 和原生 JavaScript 的交集,那么,就不得不说说需要注意的地方。
jQuery 对象实现了部分数组功能的伪数组
首先要注意的一点,就是 jQuery 对象是一个伪数组,它是对原生数组或伪数组(比如 DOM 节点列表)的封装。
如果要获得某个元素,可以用
[]
运算符或get(index)
方法;如果要获得包含所有元素的数组,可以使用toArray()
方法,或者通过 ES6 中引入的Array.from()
来转换。// 将普通数组转换成 jQuery 对象 const jo = $([1, 2, 3]); jo instanceof jQuery; // true Array.isArray(jo); // false // 从 jQuery 对象获取元素值 const a1 = jo[0]; // 1 const a2 = jo.get(1); // 2 // 将 jQuery 对象转换成普通数组 const arr1 = jo.toArray(); // [1, 2, 3] Array.isArray(arr1); // true const arr2 = Array.from(jo); // [1, 2, 3] Array.isArray(arr2); // true
注意
each/map
和forEach/map
回调函数的参数顺序jQuery 定义在
$.fn
上的each()
和map()
方法与定义在Array.prototype
上的原生方法forEach()
和map()
对应,它们的参数都是回调函数,但它们的回调函数定义有一些细节上的差别。$.fn.each()
的回调定义如下:Function(Integer index, Element element )
回调的第一个参数是数组元素所在的位置(序号,从
0
开始),第二个参数是元素本身。而
Array.prototype.forEach()
的回调定义是Function(currentValue, index, array)
回调的第一个参数是数组元素本身,第二个参数才是元素所有的位置(序号)。而且这个回调有第三个参数,即整个数组的引用。
请特别注意这两个回调定义的第一个参数和第二个参数,所表示的意义正好交换,这在混用 jQuery 和原生代码的时候很容易发生失误。
对于
$.fn.map()
和Array.prototype.map()
的回调也是如此,而且由于这两个方法同名,发生失误的概率会更大。注意
each()/map()
中的this
$.fn.each()
和$.fn.map()
回调中经常会使用this
,这个this
指向的就是当前数组元素。正是因为有这个便利,所以 jQuery 在定义回请贩时候没有把元素本身作为第一个参数,而是把序号作为第一个参数。不过 ES6 带来了箭头函数。箭头函数最常见的作用就是用于回调。箭头函数中的
this
与箭头函数定义的上下文相关,而不像普通函数中的this
是与调用者相关。现在问题来了,如果把箭头函数作为
$.fn.each()
或$.fn.map()
的回调,需要特别注意this
的使用——箭头函数中的this
不再是元素本身。鉴于这个问题,建议若非必要,仍然使用函数表达式作为$.fn.each()
和$.fn.map()
的回调,以保持原有的 jQuery 编程习惯。实在需要使用箭头函数来引用上下文this
的情况下,千万记得用其回调定义的第二个参数作为元素引用,而不是this
。// 将所有输入控制的 name 设置为其 id $(":input").each((index, input) => { // const $input = $(this) 这是错误的!!! const $input = $(input); $input.prop("name", $input.prop("id")); });
$.fn.map()
返回的并不是数组与
Array.prototype.map()
不同,$.fn.map()
返回的不是数组,而是 jQuery 对象,是伪数组。如果需要得到原生数组,可以采用toArray()
或Array.from()
输出。const codes = $([97, 98, 99]); const chars = codes.map(function() { return String.fromCharCode(this); }); // ["a", "b", "c"] chars instanceof jQuery; // true Array.isArray(chars); // false const chars2 = chars.toArray(); Array.isArray(chars2); // true
jQuery Promise
jQuery 是通过
$.Deferred()
来实现的 Promise 功能。在 ES6 以前,如果引用了 jQuery,基本上不需要再专门引用一个 Promise 库,jQuery 已经实现了 Promise 的基本功能。不过 jQuery Promise 虽然实现了
then()
,却没有实现catch()
,所以它不能兼容原生的 Promise,不过用于 co 或者 ES2017 的async/await
毫无压力。// 模拟异步操作 function mock(value, ms = 200) { const d = $.Deferred(); setTimeout(() => { d.resolve(value); }, ms); return d.promise(); }
// co 实现 co(function* () { const r1 = yield mock(["first"]); const r2 = yield mock([...r1, "second"]); const r3 = yield mock([...r2, "third"]); console.log(r1, r2, r3); }); // ['first'] // ['first', 'second'] // ['first', 'second', 'third']
// async/await 实现,需要 Chrome 55 以上版本测试 (async () => { const r1 = await mock(["first"]); const r2 = await mock([...r1, "second"]); const r3 = await mock([...r2, "third"]); console.log(r1, r2, r3); })(); // ['first'] // ['first', 'second'] // ['first', 'second', 'third']
虽然 jQuery 的 Promise 没有
catch()
,但是提供了fail
事件处理,这个事件在 Deferredreject()
的时候触发。相应的还有done
事件,在 Deferredresovle()
的时候触发,以及always
事件,不论什么情况都会触发。与一次性的
then()
不同,事件可以注册多个处理函数,在事件触发的时候,相应的处理函数会依次执行。另外,事件不具备传递性,所以fail()
不能在写在then()
链的最后。结尾
总的来说,在大量操作 DOM 的前端代码中使用 jQuery 可以带来极大的便利,也使 DOM 操作的相关代码更易读。另一方面,原生 JavaScript 带来的新特性确实可以替代 jQuery 的部分工具函数/方法,以降低项目对 jQuery 的依赖程序。
jQuery 和原生 JavaScript 应该是共生关系,而不是互斥关系。应该在合适的时候选用合适的方法,而不是那么绝对的非要用谁代替谁。
原生JS取代一些JQuery方法
1.选取元素
// jQuery var els = $('.el'); // Native var els = document.querySelectorAll('.el'); // Shorthand var $ = function (el) { return document.querySelectorAll(el); }
querySelectorAll方法返回的是NodeList对象,需要转换为数组。
myList = Array.prototype.slice.call(myNodeList)
2.创建元素
// jQuery var newEl = $('<div/>'); // Native var newEl = document.createElement('div');
3.添加事件
// jQuery $('.el').on('event', function() { }); // Native [].forEach.call(document.querySelectorAll('.el'), function (el) { el.addEventListener('event', function() { }, false); });
4.get/set属性
// jQuery $('.el').filter(':first').attr('key', 'value'); $('.el').filter(':first').attr('key'); // Native document.querySelector('.el').setAttribute('key', 'value'); document.querySelector('.el').getAttribute('key');
5.添加和移除样式Class
DOM元素本身有一个可读写的className属性,可以用来操作class。
HTML 5还提供一个classList对象,功能更强大(IE 9不支持)。
// jQuery $('.el').addClass('class'); $('.el').removeClass('class'); $('.el').toggleClass('class'); // Native document.querySelector('.el').classList.add('class'); document.querySelector('.el').classList.remove('class'); document.querySelector('.el').classList.toggle('class');
6.追加元素
尾部追加元素:
// jQuery $('.el').append($('<div/>')); // Native document.querySelector('.el').appendChild(document.createElement('div'));
头部追加元素:
//jQuery $(‘.el’).prepend('<div></div>') //Native var parent = document.querySelector('.el'); parent.insertBefore("<div></div>",parent.childNodes[0])
7.克隆元素
// jQuery var clonedEl = $('.el').clone(); // Native var clonedEl = document.querySelector('.el').cloneNode(true);
8.移除元素
Remove // jQuery $('.el').remove(); // Native remove('.el'); function remove(el) { var toRemove = document.querySelector(el); toRemove.parentNode.removeChild(toRemove); }
9.获取父级元素
// jQuery $('.el').parent(); // Native document.querySelector('.el').parentNode;
10.获取上一个/下一个元素(Prev/next element)
// jQuery $('.el').prev(); $('.el').next(); // Native document.querySelector('.el').previousElementSibling; document.querySelector('.el').nextElementSibling;
11.XHR and AJAX
// jQuery $.get('url', function (data) { }); $.post('url', {data: data}, function (data) { }); // Native // get var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = function (data) { } xhr.send(); // post var xhr = new XMLHttpRequest() xhr.open('POST', url); xhr.onreadystatechange = function (data) { } xhr.send({data: data});
12.清空子元素
//jQuery $("#elementID").empty() //Native var element = document.getElementById("elementID") while(element.firstChild) element.removeChild(element.firstChild);
13.检查是否有子元素
//jQuery if (!$("#elementID").is(":empty")){} //Native if (document.getElementById("elementID").hasChildNodes()){}
14.$(document).ready
DOM加载完成,会触发DOMContentLoaded事件,等同于jQuery的$(document).ready方法。
document.addEventListener("DOMContentLoaded", function() { // ... });
15.数据储存
jQuery对象可以储存数据。
$("body").data("foo", 52);
HTML 5有一个dataset对象,也有类似的功能(IE 10不支持),不过只能保存字符串。
element.dataset.user = JSON.stringify(user); element.dataset.score = score;
16.动画
jQuery的animate方法,用于生成动画效果。
$foo.animate('slow', { x: '+=10px' }
jQuery的动画效果,很大部分基于DOM。但是目前,CSS 3的动画远比DOM强大,所以可以把动画效果写进CSS,然后通过操作DOM元素的class,来展示动画。
foo.classList.add('animate')
如果需要对动画使用回调函数,CSS 3也定义了相应的事件。
el.addEventListener("webkitTransitionEnd", transitionEnded); el.addEventListener("transitionend", transitionEnded);
- ").append( $("").attr("href", "#").text("second")), $("

php求2个数组相同元素的方法:1、创建一个php示例文件;2、定义两个有相同元素的数组;3、使用“array_intersect($array1,$array2)”或“array_intersect_assoc()”方法获取两个数组相同元素即可。

C语言数组初始化的三种方式:1、在定义时直接赋值,语法“数据类型 arrayName[index] = {值};”;2、利用for循环初始化,语法“for (int i=0;i<3;i++) {arr[i] = i;}”;3、使用memset()函数初始化,语法“memset(arr, 0, sizeof(int) * 3)”。

Part1聊聊Python序列类型的本质在本博客中,我们来聊聊探讨Python的各种“序列”类,内置的三大常用数据结构——列表类(list)、元组类(tuple)和字符串类(str)的本质。不知道你发现没有,这些类都有一个很明显的共性,都可以用来保存多个数据元素,最主要的功能是:每个类都支持下标(索引)访问该序列的元素,比如使用语法Seq[i]。其实上面每个类都是使用数组这种简单的数据结构表示。但是熟悉Python的读者可能知道这3种数据结构又有一些不同:比如元组和字符串是不能修改的,列表可以

c++初始化数组的方法:1、先定义数组再给数组赋值,语法“数据类型 数组名[length];数组名[下标]=值;”;2、定义数组时初始化数组,语法“数据类型 数组名[length]=[值列表]”。

增加元素的方法:1、使用unshift()函数在数组开头插入元素;2、使用push()函数在数组末尾插入元素;3、使用concat()函数在数组末尾插入元素;4、使用splice()函数根据数组下标,在任意位置添加元素。

php判断数组里面是否存在某元素的方法:1、通过“in_array”函数在数组中搜索给定的值;2、使用“array_key_exists()”函数判断某个数组中是否存在指定的key;3、使用“array_search()”在数组中查找一个键值。

php去除第一个数组元素的方法:1、新建一个php文件,并创建一个数组;2、使用“array_shift”方法删除数组首个元素;3、通过“print_”r输出数组即可。

在Go语言中,数组是一种重要的数据类型。它与其他语言的数组一样,是一组相同类型的数据组成,可以通过一个索引来访问数组中的元素。在某些情况下,我们需要从一个数组中删除元素,本文将会介绍在Go语言中如何实现数组删除。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.