


Detailed explanation of how to implement the function of class selector in jquery with examples
一、类选择器的概念
类选择器,就是通过class属性获取节点。比如一个html结构中,有三个p标签都具有class=”red”的属性,那么类选择器返回的就是这三个p标签。
在jquery中,我们可以很方便的通过$(“.red”)这种方式按照类获取节点。但是在原生的javascript中,有getElementById(按照id属性获取元素)、getElementsByTagName(按照标签名获取元素)等方法,但是并没有类选择器相关方法。因此,编写原生js实现类选择器的方法非常关键。
二、类选择器的实现
通过利用原生js编写类选择器,可以更深入的了解js中的DOM相关操作,下面我们就来看一个简单的类选择器是如何实现的:
function getElementsByClass(classnames){ var classobj = newArray(); var classint = 0; var tags =document.getElementsByTagName("*"); for(var i in tags){ if(tags[i].nodeType == 1){ if(tags[i].getAttribute("class") == classnames){ classobj[classint] = tags[i]; classint++; } } } return classobj; }
我们封装了一个getElementsByClass()方法,该方法的效果是:获取所有DOM节点,它们的class属性为选定值,并返回到一个数组中。该方法传递一个参数,即需要选择的class值。
该类选择器的实现方法,首先创建一个空的数组classobj,用来存放获取到的DOM节点。classint变量用来进行索引的表示,方便数组操作。我们利用getElementsByTagName(“*”)方法获取了这个页面上的所有DOM节点(*表示匹配所有)。
取出了所有DOM节点,我们就可以进行判断了。循环遍历取到的每一个节点,如果它的nodeType是1(元素节点),则利用getAttribute(“class”)方法获取节点的class属性值,并与传递进来的class参数进行比对,如果相同,说明是我们想要的节点,存入事先定义好的数组中。最后返回该数组即可。
三、原生js类选择器测试
下面我们来验证一下我们自己编写的类选择器是否正常工作,测试代码如下:
<!DOCTYPE htmlPUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <head> <metahttp-equiv="Content-Type" content="text/html;charset=utf-8" /> <title>无标题文档</title> <scriptsrc="classtest.js"></script> <script> window.onload =function(){ var a = getElementsByClass("atest"); a[0].onmouseover = function(){ alert("class!!"); } } </script> <style> .atest{background:blue;width:200px;height:200px;margin:40px;color:white;} .btest{background:green;width:200px;height:200px;margin:40px;color:white;} </style> </head> <body> <pclass="atest">atestAAA</p> <pclass="btest">atestBBB</p> </html>
该代码我们利用我们自己封装的方法进行了测试,获取class为atest的元素,鼠标滑过后会弹出对话框。
注意我们封装的这个方法返回的是一个数组,就如同jquery中的sibling()方法一样,需要加入索引才能选中元素。如果一个页面有多个选中元素,可以利用数组循环遍历进行相应操作。
封装了一个盒jquery使用方法相同的库,每次写都有新的想法,所有代码的注释已经写到行间的注释了
/** * Created by Jason on 2016/12/31. */ //jquery 的构造函数 function Jquery(arg){ //用来存选出来的元素 this.elemenets=[]; switch(typeof arg){ case 'function' : domReady(arg); break; case 'string' : this.elements = getEle(arg); break; case 'object' : this.elements.push(arg); break; } } //DOM ready onload 如果参数是函数,则进行domReady操作 function domReady(fn){ // FF chrome if(document.addEventListener){ //jquery中已经省略false,false解决低版本火狐兼容性问题 document.addEventListener('DOMContentLoaded',fn,false); }else{ document.attachEvent('onreadystatechange',function(){ if(document.readyState=='complete'){ fn(); } }); } } function getByClass(oParent,sClass){ //高级浏览器支持getElementsByClassName直接使用 if(oParent.getElementsByClassName){ return oParent.getElementsByClassName(sClass); }else{ //不支持需要选中所有标签的类名来选取 var res=[]; var aAll=oParent.getElementsByTagName('*'); for(var i=0;i<aAll.length;i++){ //选中标签的全部类名是个str='btn on red'=aAll[i].className 使用正则 reg=/\b sClass \b/g var reg= new RegExp('\\b'+sClass+'\\b','g'); if(reg.test(aAll[i].className)){ res.push(aAll[i]); } } return res; } } //如果参数是str 进行选择器的操作 function getByStr(aParent,str){ //用来存放选中的元素的数组 这个数组在getEle存在,为了每次执行的时候都需要清空,所以使用局部函数的变量 var aChild=[]; //aParent开始是[document],再执行完getByStr的时候getEle将aParent指向了getByStr函数的返回值aChild数组以确保循环父级下面的所有匹配元素 for(var i=0;i<aParent.length;i++){ switch(str.charAt(0)){ //id选择器 eg: #box 使用document.getElementById选取 case '#': var obj=document.getElementById(str.substring(1)); aChild.push(obj); break; //类选择器 eg: .box 使用上面封装的getByClass选取 case '.': //由于一个标签可以有多个类选择器 所以需要进行循环选取 var aRes=getByClass(aParent[i],str.substring(1)); for(var j=0;j<aRes.length;j++){ aChild.push(aRes[j]); } break; //今天先简单的编写选择器 这里我们假设除了id和类选择器,就是标签选择器 default: // 如果是li.red 那么用正则来判断 if(/\w+\.\w+/g.test(str)){ //先选择标签,在选择类选择器 使用类选择器的时候重复选择器函数即可 var aStr=str.split('.'); var aRes=aParent[i].getElementsByTagName(aStr[0]); var reg=new RegExp('\\b'+aStr[1]+'\\b','g'); //循环选取标签,注意外层已经有i的循环 for(var j=0;j<aRes.length;j++){ if(reg.test(aRes[j].className)){ aChild.push(aRes[j]); } } //如果是li:eq(2) 或者 li:first这样的选择器 书写正则是的时候注意()可有可以无为? 有或者没有为* 至少有一个也就是若干个为+ {2,5}这种则为2-5个 }else if(/\w+\:\w+(\(\d+\))?/g.test(str)){ //讲str进行整理 [li,eq,2] 或者 [li,first] var aStr=str.split(/\:|\(|\)/); //aStr[2]是eq、lt、gt传入的参数,这里使用n来保存 var n=aStr[2]; //在父级下获取所有匹配aStr[0]项的标签 var aRes=aParent[i].getElementsByTagName(aStr[0]); //这时候会循环判断aStr[1]项是的内容,jquery中经常使用的为eq、lt、gt、even、odd、first、last switch(aStr[1]){ //如果是eq则把第n项传入aChild数组即可 case 'eq': aChild.push(aRes[n]); break; //如果是lt需要将aRes数组中获取到的小于n的标签循环推入aChild中 case 'lt': for(var j=0;j<n;j++){ aChild.push(aRes[j]); } break; //如果是gt则和lt相反 case 'gt': for(var j=n;j<aRes.legth;j++){ aChild.push(aRes[j]); } break; //如果是event的话需要隔数添加,注意jquery中的event是从第0开始循环的 case 'event': for(var j=0;j<aRes.length;j+=2){ aChild.push(aRes[j]); } break; //如果是odd的和event不同的只是从第1项开始循环 case 'odd': for(var j=1;j<aRes.length;j+=2){ aChild.push(aRes[j]); } break; //如果是first,则将aRes[0]推入aChild case 'first': aChild.push(aRes[0]); break; case 'last': aChild.push(aRes[aRes.length-1]); break; } //属性选择器 eg:input[type=button] 同样适用正则来判断 }else if(/\w+\[\w+\=\w+\]/g.test(str)){ //将属性选择器切成数组 [input,type,button] var aStr=str.split(/\[|\=|\]/g); var aRes=aParent[i].getElementsByTagName(aStr[0]); //在选中标签中选出有aRes[1]的属性 for(var j=0;j<aRes.length;j++){ //把属性值为aRes[2]的标签推入aChild中 if(aRes[j].getAttribute(aStr[1])==aStr[2]){ aChild.push(aRes[j]); } } //标签选择器 p、span }else{ var aRes=aParent[i].getElementsByTagName(str); for(var j=0;j<aRes.length;j++){ aChild.push(aRes[j]); } } break; } } return aChild; } function getEle(str){ //如果是字符串的话先要去除收尾空格 eg:" on replace index play auto " var arr = str.replace(/^\s+|\s+$/g,'').split(/\s+/g); var aChild = []; var aParent = [document]; for(var i = 0;i<arr.length;i++){ aChild = getByStr(aParent,arr[i]); aParent = aChild } return aChild; } //实现jquery $符号的写法 function $(arg){ return new Jquery(arg); }
The above is the detailed content of Detailed explanation of how to implement the function of class selector in jquery with examples. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.
