这次给大家带来js仿jquery步骤详解,js仿jquery的注意事项有哪些,下面就是实战案例,一起来看一下。
最近迷上了原生js,能不用jquery等框架的情况都会手写一些js方法,记得刚接触前端的时候为了选择器而使用jquery。。。现在利用扩展原型的方法实现一些jquery函数:
1.显示/隐藏
//hide() Object.prototype.hide = function(){ this.style.display="none"; return this; } //show() Object.prototype.show = function(){ this.style.display="block"; return this; }
return this的好处在于链式调用。
2.滑动 省略speed和callback的传入,因为要加一串判断和处理回调,代码量大
//slideDown() Object.prototype.slideDown = function(){ this.style.display = 'block'; if(this.clientHeight<this.scrollheight object.prototype.slideup>0){ this.style.height=this.clientHeight-10+"px"; var _this = this; setTimeout(function(){_this.slideUp()},10) }else{ this.style.height=0; this.style.display = 'none'; } }</this.scrollheight>
3.捕获/设置
//attr() Object.prototype.attr = function(){ if(arguments.length==1){ return eval("this."+arguments[0]); }else if(arguments.length==2){ eval("this."+arguments[0]+"="+arguments[1]); return this; } } //val() Object.prototype.val = function(){ if(arguments.length==0){ return this.value; }else if(arguments.length==1){ this.value = arguments[0]; return this; } } //html() Object.prototype.html = function(){ if(arguments.length==0){ return this.innerHTML; }else if(arguments.length==1){ this.innerHTML = arguments[0]; return this; } } //text()需要在html()结果基础上排除标签,会很长,省略
4.CSS方法
//css() Object.prototype.css = function(){ if(arguments.length==1){ return eval("this.style."+arguments[0]); }else if(arguments.length==2){ eval("this.style."+arguments[0]+"='"+arguments[1]+"'"); return this; } }
5.添加元素
//append() Object.prototype.append = function(newElem){ this.innerHTML += newElem; return this; } //prepend() Object.prototype.prepend = function(newElem){ this.innerHTML = arguments[0] + this.innerHTML; return this; } //after() Object.prototype.after = function(newElem){ this.outerHTML += arguments[0]; return this; } //before() Object.prototype.before = function(newElem){ this.outerHTML = arguments[0] + this.outerHTML; return this; }
6.删除/替换元素
//empty() Object.prototype.empty = function(){ this.innerHTML = ""; return this; } //replaceWith() Object.prototype.replaceWith = function(newElem){ this.outerHTML = arguments[0]; return this; } //remove() js自带,省略。
7.设置css类
//hasClass() Object.prototype.hasClass = function(cName){ return !!this.className.match( new RegExp( "(\\s|^)" + cName + "(\\s|$)") ); } //addClass() Object.prototype.addClass = function(cName){ if( !this.hasClass( cName ) ){ this.className += " " + cName; } return this; } //removeClass() Object.prototype.removeClass = function(cName){ if( this.hasClass( cName ) ){ this.className = this.className.replace( new RegExp( "(\\s|^)" + cName + "(\\s|$)" )," " ); } return this; }
上面的设置CSS类也可以利用html5新API classList及contains实现 但不兼容IE8以下及部分火狐浏览器
Object.prototype.hasClass = function(cName){ return this.classList.contains(cName) } Object.prototype.addClass = function(cName){ if( !this.hasClass( cName ) ){ this.classList.add(cName); } return this; } Object.prototype.removeClass = function(cName){ if( this.hasClass( cName ) ){ this.classList.remove(cName); } return this; }
9.选择器
//id或class选择器$("elem") function $(strExpr){ var idExpr = /^(?:\s*()[^>]*|#([\w-]*))$/; var classExpr = /^(?:\s*()[^>]*|.([\w-]*))$/; if(idExpr.test(strExpr)){ var idMatch = idExpr.exec(strExpr); return document.getElementById(idMatch[2]); }else if(classExpr.test(strExpr)){ var classMatch = classExpr.exec(strExpr); var allElement = document.getElementsByTagName("*"); var ClassMatch = []; for(var i=0,l=allElement.length; i<l><p style="text-align: left;">需要强调的是,选择器返回的结果或结果集包含的是htmlDOM,并非jquery的对象。大多数人都知道,document.getElementById("id")等价于jquery$("#id")[0],另外上面class选择器选择的结果如需使用,需要利用forEach遍历:</p> <pre class="brush:php;toolbar:false">$(".cls").forEach(function(e){ e.css("background","#f6f6f6") })
10.遍历 siblings()和children()获取的结果也需要结合forEach使用
//siblings() Object.prototype.siblings = function(){ var chid=this.parentNode.children; var eleMatch = []; for(var i=0,l=chid.length;i<l object.prototype.userchildren object.prototype.parent object.prototype.next object.prototype.prev><p style="text-align: left;">jquery事件函数原生js已有,另外,原生js实现jquery的一个<a href="http://www.php.cn/code/5392.html" target="_blank">常用函数</a> ajax 将会在下一篇写道。</p> <p style="text-align: left;"><strong>原生js实现ajax方法</strong></p> <p>相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!</p> <p>推荐阅读:</p> <p><a href="http://www.php.cn/js-tutorial-393821.html" target="_blank">JS中时间单位比较的方法</a><br></p> <p><a href="http://www.php.cn/js-tutorial-393817.html" target="_blank">JS操作JSON详细介绍</a><br></p></l>
The above is the detailed content of Detailed explanation of js imitation jquery steps. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version
Chinese version, very easy to use

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

Atom editor mac version download
The most popular open source editor
