jQuery是个好东西。它诞生于IE6在互联网称霸的那个时代。jQuery的存在让我们的代码能很好的兼容各种平台。

然而,到如今,浏览器技术已经取得了巨大的进步。我们可以自由的使用所有最新众多ES5/ES6提供的原生API,配合革命性的HTML5 API,我们对DOM的操作变得从未如此的容易。WEB开发人员突然发现,没有jQuery其实也能轻松高效的完成项目开发。

不要误会,jQuery仍然是一个强大的工具包,大多时候我们还是要优先选择它。然而,对于一些简单的任务,一些小项目,一个简单的页面,或者移动版网站上,我们使用简单的纯js也许更有效率。下面的10个技巧希望能给大家一些启发。

1. 监听页面加载完成事件

写jQuery代码时,我们通常首先做的是把代码包裹在$(document).ready()里,这样,当DOM加载完成,可以操作时,包裹的代码才会去执行。除了使用jQuery,我们还可以使用 DOMContentLoaded 事件代替,下面是用例:

/ Add an event listener of DOMContentLoaded to the whole document and call an anonymous function.
// You can then wrap your code in that function's brackets
// and it will execute once loading is complete.document.addEventListener('DOMContentLoaded', function () {// Our hawaiian greeting is displayed as soon as the page loads,console.log('Aloha');});

  

2. 查找/选择页面元素

曾经,我们如果想捕捉一个/一批元素,只能通过 id, class 和 tag 名称,jQuery给我提供了革命性的更具灵活性的基于css的查找方法。随着浏览器的进步,我们现在可以使用两个新型的原生JavaScript API – querySelector 和querySelectorAll:

// We can use document.querySelector to get the first element that matches a certain criteria.
// It's only argument is a string containing one or more CSS selectors.var lochNess = document.querySelector(".monsters");console.log("It's from Scotland - " + lochNess.textContent);// We can also get all elements of a certain type or class by using document.querySelectorAll.
// This returns a NodeList of all the elements that fit our criteria.var scary = document.querySelectorAll(".monsters");console.log("Hide and seek champions: ");for (var i = 0; i < scary.length; i++) {console.log(scary[i].innerHTML);}

 

<ul><li class="monsters">Nessy</li><li class="monsters">Big foot</li><li class="monsters">La chupacabra</li></ul>

  

3. 添加和移除事件监听器

事件监听是WEB应用里非常常见的操作。在过去,IE里的事件监听和其它浏览器的监听方法是不统一/不兼容的。但如今,我们只需要使用addEventListener就可以了:

var btn = document.querySelectorAll("button"),list = document.querySelector("ul");// We call the addEventListener method on our desired event target(in this case a button).
// This will start a listener that will wait until a click is generated on the element.btn[0].addEventListener("click", function () {// When this button is clicked we want to enable zooming of our list.// To do this we add an event listener to our list itself,// so when the cursor hovers it, the enlarge function gets called.list.addEventListener("mouseover", enlarge);
});// To disable the zooming we can simply use removeEventListener.btn[1].addEventListener("click", function () {// Removing event listeners doesn't work on anonymous functions, so always use a named one.list.removeEventListener("mouseover", enlarge);
});// Let's create our enlarge function.var enlarge = function () {// Add class zoomed to the unordered list.list.classList.add("zoomed");// When the cursor leaves the list return to normal size by removing the class.list.addEventListener("mouseout", function () {list.classList.remove("zoomed")});};// Now we want to be able to color the names by clicking them.// When a 'click' is registered on one of the list entries it should change its color to green.
// Thanks to event delegation we can actually add an event listener to the whole parent object.
// This way we don't have to add separate event listeners to each <li>.list.addEventListener("click", function (e) {// Make the coloring happen only to the clicked element by taking the target of the event.e.target.classList.add('green');});

  

<button>Enable zoom</button><button>Disable zoom</button><br><br>Click on any of the names to color them green<ul><li>Chewbacca</li><li>Han Solo</li><li>Luke</li><li>Boba fett</li></ul>

  

.green {color: green;
}.zoomed {cursor: pointer;font-size: 23px;
}

  

addEventListener 的用法看起来跟jQuery里的事件监听用法非常相似。

4. 对类和属性的操作

以前,执行对于页面元素css类的各种操作(查找、增加、删除等),如果不用jQuery,那是一件非常麻烦的事情。这样的历史已经一去不复返了,这样要感谢classList 属性。而使用 setAttribute, 我们可对元素属性进行操作。

var btn = document.querySelectorAll("button"),div = document.querySelector("#myDiv");btn[0].addEventListener("click", function () {// Get any attribute easily.console.log(div.id);
});// Element.classList stores all classes of the element in the form of a DOMTokenList.var classes = div.classList;btn[1].addEventListener("click", function () {console.log(classes);});btn[2].addEventListener("click", function () {// 可以增加和移除某个类名classes.add("red");});btn[3].addEventListener("click", function () {// 可以翻转某个类名classes.toggle("hidden");});

  

<div id='myDiv' class="square"></div><button>Display id</button><button>Display classes</button>
<button>Color red</button>
<button>Toggle visibility</button>

  

.square {width: 100px;height: 100px;margin-bottom: 20px;border: 1px solid grey;border-radius: 5px;
}.hidden {visibility: hidden;
}.red {background-color: red;
}

  

5. 获取或设置元素的内容

jQuery里有个非常方便的 text() 和 html() 方法,相对应的,在元素JavaScript里,我们可以使用 textContent 和 innerHTML 两个属性,这两个属性其实并不是新出现的:

var myText = document.querySelector("#myParagraph"),btn = document.querySelectorAll("button");// We can easily get the text content of a node and all its descendants.var myContent = myText.textContent;console.log("textContent:  " + myContent);// When using textContent to alter the text of an element
// it deletes the old content and replaces it with new.btn[0].addEventListener('click', function () {myText.textContent = " Koalas are the best animals ";});// If we want to grab all the HTML in a node (including the tags) we can use innerHTML.var myHtml = myText.innerHTML;console.log("innerHTML:  " + myHtml);// To change the html simply supply new content.
// Of course we aren't limited to text only this time.btn[1].addEventListener('click', function () {myText.innerHTML = "<button> Penguins are the best animals </button>";});

  

<p id="myParagraph"><strong> Which are the best animals? </strong></p><button>Koalas</button><br><button>Penguins</button>

  

6. 循环数组

jQuery里提供了很多实验的方法,比如each() 和 map(),而在新版的JavaScript api里,我们有了原生的 forEach 和 map ,需要注意的是,它们参数的用法有些不同,并且在回调函数里 this 的代表性也有些不同。

var ninjaTurtles = ["Donatello", "Leonardo", "Michelangelo", "Raphael"];// ForEach automatically iterates through an array.ninjaTurtles.forEach(function (entry) {console.log(entry);
});// The map method calls a function on every element of an array and creates a new array with the results.var lovesPizza = ninjaTurtles.map(function (entry) {return entry.concat(" loves pizza!");});console.log(lovesPizza);

  

7. AJAX

新版的JavaScript API里提供了一个全新的可以实现ajax的API——fetch,这个api采用了全新的 Promise 架构,使用起来更方便,更灵活,详细用法请参考《你不需要jQuery(三):新AJAX方法fetch() 》。

总结

如果你追求极简,不允许页面有半点臃肿,以更快的加载速度和更好的用户体验为目标,那么,你应该试试上面的技巧,不要因为一个很小的功能而滥用jQuery,浏览器在革新,JavaScript在进步,原生的API逐渐取代jQuery是潮流,WEB程序员应多关注这方面的知识技巧,不是吗?

 

转载于:https://www.cnblogs.com/xupeiyu/p/5067051.html

你不需要jQuery(四)相关推荐

  1. 从零开始学习jQuery (四) 使用jQuery操作元素的属性与样式

    本系列文章导航 从零开始学习jQuery (一) 开天辟地入门篇 从零开始学习jQuery (二) 万能的选择器 从零开始学习jQuery (三) 管理jQuery包装集 从零开始学习jQuery ( ...

  2. jQuery四、其他方法

    零.文章目录 jQuery四.其他方法 1.jQuery 拷贝对象 如果想要把某个对象拷贝(合并) 给另外一个对象使用,此时可以使用 $.extend() 方法 $.extend([deep], ta ...

  3. [乐意黎转载]从零开始学习jQuery (四) 使用jQuery操作元素的属性与样式

    一.摘要 本篇文章讲解如何使用jQuery获取和操作元素的属性和CSS样式. 其中DOM属性和元素属性的区分值得大家学习. 二.前言 通过前面几章我们已经能够完全控制jQuery包装集了,  无论是通 ...

  4. Web前端第四季(jQuery):四:301-jQuery基本过滤器(奇数和偶数)+302-实现隔行换色+401-祖先选择器和子代选择器

    目录 一.目的 1.想:学习前端知识 2.想:记录笔记,下次不用看视频,直接看笔记就可以快速回忆. 二.参考 1.我自己代码的GitHub网址 2.SIKI学院:我参考此视频实操 3.w3school ...

  5. jQuery四:获取、设置、移除属性;attr(“href“)、attr(“href“,“http://www.baidu.com“)、removeAttr(“href“);

    attr()方法是用于设置标签的属性,比如src,href,title:(这些更多的是元素的基本属性,HTML的属性): 目录 一:操作元素属性 (1)attr()方法:只传一个参数:获取属性 (2) ...

  6. JQuery(四) 对象数组进行排序

    一.升序 //对数组进行排序function compare(property) {return (firstobj, secondobj) => {const firstValue = fir ...

  7. 跟我学jQuery(三) 无所不能的选择器1

    跟我学jQuery教程目录: 跟我学jQuery(一)    前言 跟我学jQuery(二)    初识jQuery 跟我学jQuery(三)    无所不能的选择器1 跟我学jQuery(四)    ...

  8. 系列文章--jQuery教程

    从零开始学习jQuery (一) 开天辟地入门篇 从零开始学习jQuery (二) 万能的选择器 从零开始学习jQuery (三) 管理jQuery包装集 从零开始学习jQuery (四) 使用jQu ...

  9. js、jquery实用小技巧集合

    Tip16:JS的定时器 JS 中有两种定时器,setTimeout('fn', t) 和 setInterval('fn', t),'fn'指的是定时执行的方法名,字符串类型. setTimeout ...

最新文章

  1. c语言 获取文件名的相对路径,c – 如何获取对应于给予dlopen的相对路径的绝对库文件名?...
  2. 如何完美的将对话框设置成无边框无标题栏样式?
  3. wxWidgets:wxListItem类用法
  4. 串口的输出设置【原创】
  5. python如何将数据保存到本地json文件
  6. java OOP及相关基础知识汇总(转)
  7. 换个思路理解Javascript中的this
  8. Nginx篇05-http长连接和keeplive
  9. 浏览器扩展应用安装AXURE插件
  10. 送给计算机老师平安夜贺卡,给老师的平安夜祝福语
  11. PTA 1096 大美数(Python3)
  12. stata学习笔记|基本知识
  13. 宝马项目化流程标准(BMW ABC flyer requirement)
  14. 深圳活动会议媒体邀约,电视台,网媒媒体资源
  15. 将字符串中的小写字母转换为相应的大写字母
  16. 华师大计算机学院院士,华师大新建4大学院1个研究院顺应AI发展
  17. 【子桓说】西安女硕士:我挺感谢新媒体的
  18. 插入排序监视哨和鸡尾酒排序
  19. 三只松鼠前高管盗卖废旧纸箱获利68万被判刑
  20. 东南亚(Lazada shoppe)自养号测评如何解决收货地址及ip问题详解

热门文章

  1. 深度学习背后的基础-神经网络揭秘
  2. 芯片植入:“增强人类”的生物黑科技
  3. 华为云力推“普惠AI”,EI智能体正在落地行业
  4. 国际互联网协会(ISOC)提出未来互联网十项原则
  5. 德勤:2018年科技、传媒和电信行业未来趋势预测
  6. 博通收购高通12张PPT深度解析!
  7. 据说只有程序员才看得懂 | 每日趣闻
  8. 关于Input内容改变的触发事件
  9. jQuery判断checkbox是否选中
  10. 活动目录系列之三---域控制器常规卸域