Home Web Front-end Front-end Q&A How to use jquery package

How to use jquery package

May 25, 2023 pm 03:10 PM

Preface

In web development, JavaScript has become a necessary tool. And the jQuery library is undoubtedly one of the most popular JavaScript libraries. It provides a simple and easy-to-use API that can help us operate DOM, Ajax, event processing, etc. more efficiently. This article will introduce how to use jQuery, suitable for beginners.

1. Install jQuery

Before we begin, we need to install jQuery first.

  1. Download jQuery on the official website

We can download the latest version of jQuery.zip or jQuery.min.js file on the jQuery official website. Download website: https://jquery.com/download/

  1. Use CDN (Content Delivery Network)

Using CDN can obtain jQuery files more efficiently and without Need to store it locally.

The following are two commonly used jQuery CDNs:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Copy after login

2. Use jQuery to select elements

jQuery uses selector syntax to select elements and provides easy-to-use API to operate these elements.

  1. Basic selectors

You can use the following predefined basic selectors to select HTML elements:

$("element")              匹配所有给定元素。
$(".class")               匹配所有给定类名的元素。
$("#id")                  匹配所有给定 id 的元素。
Copy after login

For example:

$("p")   //匹配所有的 <p> 标签
$(".intro")  //所有类名为 "intro" 的元素
$("#demo")   //id 为 demo 的元素
Copy after login
  1. Hierarchical selector

You can use the hierarchical selector to select elements with specific relationships:

$("parent>child")         匹配父元素下的子元素。
$("prev + next")          匹配紧接在 prev 元素之后的 next 元素。
$("prev ~ siblings")      匹配 prev 元素之后的所有同级 siblings 元素。
Copy after login

For example:

$("div>p")  //匹配 <div> 中所有 <p> 元素
$("h1+p")   //所有 <h1> 元素后直接跟着的 <p> 元素
$("h1~p")   //所有 <h1> 元素后的同级 <p> 元素
Copy after login
  1. Filter selector

Filter selector filters based on selected elements. The following are some examples of filter selectors:

:first                    选择序列中的第一个元素。
:last                     选择序列中的最后一个元素。
:even                     选择序列中索引为偶数(从 0 开始)的元素。
:odd                      选择序列中索引为奇数(从 0 开始)的元素。
:eq(index)                选择序列中索引指定为 index 的元素。
:gt(no)                   选择索引大于 no 的元素。
:lt(no)                   选择索引小于 no 的元素。
Copy after login

For example:

$("li:first")  //选取列表中的第一个 <li> 元素
$("li:last")   //选取列表中的最后一个 <li> 元素
$("li:even")   //选取列表中的偶数 <li> 元素
$("li:eq(1)")  //选取列表中第二个 <li> 元素
Copy after login

3. jQuery operates DOM elements

We can modify, add or remove page elements through jQuery.

  1. New elements

You can use the following methods to create new HTML elements:

$(html)            从字符串中创建元素。
$("<element>")     创建元素。
$("<element>", {    创建设置元素属性的元素。
    html: "",
    css: "",
    id: ""
})
Copy after login

For example:

$("p").after("<p>Hello World!</p>");  //在所有的 <p> 元素后添加一个 <p> 元素
Copy after login
  1. Delete element

You can use the remove() method to delete an element:

$("element").remove();              从页面中删除元素。
Copy after login

For example:

$("p").remove();  //删除所有的 <p> 元素
Copy after login
  1. Change element

jQuery has a series of methods for modifying the attributes and content of elements, among which the attr() and text() methods are the most commonly used.

$("element").attr("attribute", "value")    改变元素的属性。
$("element").html(content)                 更改元素的内容。
$("element").text(content)                 更改元素的文本内容。
Copy after login

For example:

$("img").attr("src", "new_src.jpg");  //更改图片的 src 属性
$("<p>").text("Hello World!");       //创建一个新的 <p> 元素,以文本 Hello World! 作为其内容
Copy after login

4. Traversing elements

jQuery has the following methods of traversing elements:

next()                  返回下一个兄弟元素。
prev()                  返回前一个兄弟元素。
parent()                返回当前元素的直接父元素。
parents()               返回当前元素的所有先辈元素。
find()                  查找匹配选择器的后代元素。
Copy after login

For example:

$("p").next()     //返回第一个 <p> 元素的下一个兄弟元素
$("p").parent()   //返回第一个 <p> 元素的直接父元素
$("p").parents()  //返回第一个 <p> 元素的所有先辈元素
Copy after login

5. Event handling

You can use the following methods to bind event handlers:

click()                 当元素被点击时运行的函数。
mouseover()             当指针移动到元素上时运行的函数。
keydown()               当键盘上按下键时运行的函数。
submit()                当提交表单时运行的函数。
ready()                 当文档被加载时运行的函数。
Copy after login

For example:

$("button").click(function(){
    alert("Button Clicked!");
});
Copy after login

6. Ajax

jQuery uses AJAX ( Asynchronous JavaScript and XML) to dynamically update content on a web page without reloading the entire page.

jQuery can use the $.ajax() or $.get() function to send requests, and the $.parseJSON() or $.getJSON() function to process JSON data from the server.

For example:

$.ajax({
    url: "demo.txt",
    success: function(result){
        $("div").html(result);
    }
});
Copy after login

Conclusion

This article introduces the basics of jQuery, including installation, selecting elements, manipulating DOM elements, traversing elements, event handling, and AJAX. Of course, there are many advanced uses of jQuery that require in-depth study and understanding.

The above is the detailed content of How to use jquery package. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

Frontend Development with React: Advantages and Techniques Frontend Development with React: Advantages and Techniques Apr 17, 2025 am 12:25 AM

The advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.

React and the Frontend: Building Interactive Experiences React and the Frontend: Building Interactive Experiences Apr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React's Ecosystem: Libraries, Tools, and Best Practices React's Ecosystem: Libraries, Tools, and Best Practices Apr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

The Future of React: Trends and Innovations in Web Development The Future of React: Trends and Innovations in Web Development Apr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

React vs. Backend Frameworks: A Comparison React vs. Backend Frameworks: A Comparison Apr 13, 2025 am 12:06 AM

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

React: The Power of a JavaScript Library for Web Development React: The Power of a JavaScript Library for Web Development Apr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

Understanding React's Primary Function: The Frontend Perspective Understanding React's Primary Function: The Frontend Perspective Apr 18, 2025 am 12:15 AM

React's main functions include componentized thinking, state management and virtual DOM. 1) The idea of ​​componentization allows splitting the UI into reusable parts to improve code readability and maintainability. 2) State management manages dynamic data through state and props, and changes trigger UI updates. 3) Virtual DOM optimization performance, update the UI through the calculation of the minimum operation of DOM replica in memory.

See all articles