search
HomeWeb Front-endJS TutorialAbout jQuery Reference Example 1.0 The Philosophy of jQuery_jquery

This article is translated from jQuery Cookbook (O'Reilly 2009) 1.0 The jQuery Philosophy

The philosophy of jQuery is "Write less code, do more things". This philosophy can be divided into three concepts:

  • Find elements with CSS selectors and manipulate them with jQuery methods
  • Chaining multiple jQuery methods on a set of elements
  • jQuery encapsulation and implicit traversal

Fully understanding these three concepts is crucial to writing jQuery code. Let’s take a closer look at these three concepts.

Find elements and operate on them

To be more precise, it is to locate a batch of elements in the DOM tree and then operate on the set of elements. For example, the following example: first hide a

element from the user, then insert some new text into the hidden
element, then change its attributes, and finally redisplay the
element. The corresponding jQuery code is as follows:
<SPAN class=dec><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"></SPAN><SPAN class=pln>
</SPAN><SPAN class=tag><html></SPAN><SPAN class=pln>
</SPAN><SPAN class=tag><head></SPAN><SPAN class=pln>
 </SPAN><SPAN class=tag><script</SPAN><SPAN class=pln> </SPAN><SPAN class=atn>type</SPAN><SPAN class=pun>=</SPAN><SPAN class=atv>"text/JavaScript"</SPAN><SPAN class=pln>
  </SPAN><SPAN class=atn>src</SPAN><SPAN class=pun>=</SPAN><SPAN class=atv>"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"</SPAN><SPAN class=tag>></script></SPAN><SPAN class=pln>
</SPAN><SPAN class=tag></head></SPAN><SPAN class=pln>
</SPAN><SPAN class=tag><body></SPAN><SPAN class=pln>
 </SPAN><SPAN class=tag><div></SPAN><SPAN class=pln>old content</SPAN><SPAN class=tag></div></SPAN><SPAN class=pln>
 </SPAN><SPAN class=tag><script></SPAN><SPAN class=pln>
  </SPAN><SPAN class=com>//隐藏页面上所有的div元素</SPAN><SPAN class=pln>
  jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'div'</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>hide</SPAN><SPAN class=pun>();</SPAN><SPAN class=pln>
  </SPAN><SPAN class=com>//更新所有div元素内的文本</SPAN><SPAN class=pln>
  jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'div'</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>text</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'new content'</SPAN><SPAN class=pun>);</SPAN><SPAN class=pln>
  </SPAN><SPAN class=com>//在所有的div元素上添加值为updatedContent的class属性</SPAN><SPAN class=pln>
  jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'div'</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>addClass</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>"updatedContent"</SPAN><SPAN class=pun>);</SPAN><SPAN class=pln>
  </SPAN><SPAN class=com>//显示页面上所有的div元素</SPAN><SPAN class=pln>
  jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'div'</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>show</SPAN><SPAN class=pun>();</SPAN><SPAN class=pln>
 </SPAN><SPAN class=tag></script></SPAN><SPAN class=pln>
</SPAN><SPAN class=tag></body></SPAN><SPAN class=pln>
</SPAN><SPAN class=tag></html></SPAN>

Let’s take a look at these four jQuery statements one by one:

  • Hide all div elements on the page, making them invisible
  • Replace the original text in the hidden div element with new text ('new content')
  • Add a new class attribute value (updatedContent) to the div element
  • Redisplay the div element on the page

The above example uses the jQuery function to find all

elements in the HTML page, and then uses jQuery methods to operate on them (hide(), text(), addClass(), show()).

Chain call

When calling jQuery methods, according to the design of jQuery, these methods can be called in a chain. For example, only perform an element search once, and then perform a series of operations on the found elements. The previous code example can be rewritten as a JavaScript statement using chained calls.

Using chain calls, you can use the following code:

<SPAN class=com>//隐藏页面上所有的div元素</SPAN><SPAN class=pln>
jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'div'</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>hide</SPAN><SPAN class=pun>();</SPAN><SPAN class=pln>
</SPAN><SPAN class=com>//更新所有div元素内的文本</SPAN><SPAN class=pln>
jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'div'</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>text</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'new content'</SPAN><SPAN class=pun>);</SPAN><SPAN class=pln>
</SPAN><SPAN class=com>//在所有的div元素上添加值为updatedContent的class属性</SPAN><SPAN class=pln>
jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'div'</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>addClass</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>"updatedContent"</SPAN><SPAN class=pun>);</SPAN><SPAN class=pln>
</SPAN><SPAN class=com>//显示页面上所有的div元素</SPAN><SPAN class=pln>
jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'div'</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>show</SPAN><SPAN class=pun>();</SPAN>

is rewritten as:

<SPAN class=pln>jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'div'</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>hide</SPAN><SPAN class=pun>().</SPAN><SPAN class=pln>text</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'new content'</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>addClass</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>"updatedContent"</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>show</SPAN><SPAN class=pun>();</SPAN>

If you add code indentation it will be:

<SPAN class=pln>jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'div'</SPAN><SPAN class=pun>)</SPAN><SPAN class=pln>
 </SPAN><SPAN class=pun>.</SPAN><SPAN class=pln>hide</SPAN><SPAN class=pun>()</SPAN><SPAN class=pln>
 </SPAN><SPAN class=pun>.</SPAN><SPAN class=pln>text</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'new content'</SPAN><SPAN class=pun>)</SPAN><SPAN class=pln>
 </SPAN><SPAN class=pun>.</SPAN><SPAN class=pln>addClass</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>"updatedContent"</SPAN><SPAN class=pun>)</SPAN><SPAN class=pln>
 </SPAN><SPAN class=pun>.</SPAN><SPAN class=pln>show</SPAN><SPAN class=pun>();</SPAN>

Simply put, chained calls allow unlimited jQuery methods to be used together on the currently selected set of elements. In essence, elements processed with jQuery methods will always be returned after the method is processed, so the chain of calls can continue. The jQuery plug-in is also designed in this way (returning an encapsulated element set), so using the plug-in does not affect the chain call.

Another benefit of chained calls is that it saves overhead by selecting DOM elements only once. Avoiding traversing the DOM tree is crucial to improving web page performance, so it is necessary to reuse or cache the selected set of DOM elements as much as possible.

jQuery wrapper

In most cases, if you use jQuery, you will definitely deal with something called "jQuery encapsulation". In other words, elements selected from an HTML page using jQuery will be encapsulated with a layer of functionality provided by jQuery. I personally like to call this thing "encapsulated element set" because it is a set of elements that encapsulates jQuery functions. This set of encapsulated elements sometimes contains one DOM element, sometimes it contains multiple, and sometimes it contains nothing at all. When the set of encapsulating elements is empty, jQuery methods/properties called on it will not throw any errors - this avoids unnecessary if statements.

Using the above HTML code as an example, what happens when there are multiple

elements in the web page? In the example below, the HTML page has three more
elements:
<SPAN class=dec><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"></SPAN><SPAN class=pln>
</SPAN><SPAN class=tag><html></SPAN><SPAN class=pln>
</SPAN><SPAN class=tag><head></SPAN><SPAN class=pln>
 </SPAN><SPAN class=tag><script</SPAN><SPAN class=pln> </SPAN><SPAN class=atn>type</SPAN><SPAN class=pun>=</SPAN><SPAN class=atv>"text/JavaScript"</SPAN><SPAN class=pln> </SPAN><SPAN class=atn>src</SPAN><SPAN class=pun>=</SPAN><SPAN class=atv>"http://ajax.googleapis.com/ajax/libs/
  jquery/1.3.0/jquery.min.js"</SPAN><SPAN class=tag>></script></SPAN><SPAN class=pln> </SPAN><SPAN class=tag></head></SPAN><SPAN class=pln>
</SPAN><SPAN class=tag><body></SPAN><SPAN class=pln>
 </SPAN><SPAN class=tag><div></SPAN><SPAN class=pln>old content</SPAN><SPAN class=tag></div></SPAN><SPAN class=pln>
 </SPAN><SPAN class=tag><div></SPAN><SPAN class=pln>old content</SPAN><SPAN class=tag></div></SPAN><SPAN class=pln>
 </SPAN><SPAN class=tag><div></SPAN><SPAN class=pln>old content</SPAN><SPAN class=tag></div></SPAN><SPAN class=pln>
 </SPAN><SPAN class=tag><div></SPAN><SPAN class=pln>old content</SPAN><SPAN class=tag></div></SPAN><SPAN class=pln>
 </SPAN><SPAN class=tag><script></SPAN><SPAN class=pln>
  jQuery</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'div'</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>hide</SPAN><SPAN class=pun>().</SPAN><SPAN class=pln>text</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>'new content'</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>addClass</SPAN><SPAN class=pun>(</SPAN><SPAN class=str>"updatedContent"</SPAN><SPAN class=pun>).</SPAN><SPAN class=pln>show</SPAN><SPAN class=pun>();</SPAN><SPAN class=pln>
 </SPAN><SPAN class=tag></script></SPAN><SPAN class=pln>
</SPAN><SPAN class=tag></body></SPAN><SPAN class=pln>
</SPAN><SPAN class=tag></html></SPAN>

In the above example there is no programming code representing a loop. But the wonderful thing is that jQuery will scan the entire page, then put all

elements into the encapsulated element set, and then execute a series of jQuery methods defined by the code for each element in the encapsulated set (implicit traversal). For example, every element in the encapsulated set calls .hide(). In the above code, in fact, every method we use (hide(), text(), addClass(), show()) has an effect on all div elements in the page, just like a human-written loop The same way to iterate over DOM elements. The execution result of the above code is: every
element in the page is hidden, the contained text is changed, the class attribute is added, and finally reappears.

Being familiar with encapsulated element sets and implicit traversal is very important for writing complex looping logic - it is important to note that before writing any additional looping code, a simple looping operation already exists (for example: jQuery(' div').each(function(){}). In other words, the call to the jQuery method affects every element in the encapsulated element set.

It should be noted that some jQuery methods have special behavior and will only affect the first element in the set of encapsulated elements (for example: attr()).

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

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.

MantisBT

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

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment