search
HomeWeb Front-endJS TutorialSummary of common knowledge points of jQuery and encapsulation of commonly used functions_jquery

This article introduces you to the common knowledge points and functions in jQuery, including many detailed knowledge. Let’s learn together.

jQuery provides us with many useful attributes and some commonly used functions that I have summarized. Personally, I think it is more commonly used in online layout development, and is only for everyone's learning and reference.

I started organizing this document when I first started learning front-end, and now the content has gradually increased. Although it seems that the content in the document is very simple now, looking at the content, it seems that I still vaguely remember the scene when this line of code was recorded. So I want to save this memory and provide a simple query method for children who are new to the front-end, and also to remember my front-end learning journey.

** I will continue to update this document **
-------------------------------------------------- ----------------------------------

Jquery common knowledge points

jquery effect

Hide/Show:

hide/show(speed,callback); speed(空/slow/fast/毫秒)
$("#hide").click(function(){
$("p").hide();//隐藏 p标签;
$("p").show();//显示 p=标签;
});

Fade in/out:

fadeIn/fadeout(speed,callback)
$(“#click”).click(function(){
$(“#div1”).fadeIn();//直接显示;
$(“#div2”).fadeIn(“slow”);//慢慢显示;
$(“#div3”).fadeIn(3000);//用3秒时间显示;
})

Slide: slideDown/slideUp(speed,callback)

$(“#click”).click(function(){
$(“#div1”).slideDown();//直接下滑;
$(“#div2”).slideDown(“slow”);//慢慢下滑;
$(“#div3”).slideDown (3000);//用3秒时间下滑;
})

Animation:

$(".btn1").click(function(){
$("#box").animate({
height:"300px", 
width:"300px"
}); //将宽高变为300px;
});

jQuery DOM

Get text value and attribute value:

<p id=”test”>这是一段文字中的<b>粗体</b></p>
<input id=”input” value=”文本值”/>
<a id=”a” href=”http://...”></a> 

js code:

$(“#test”).text();//输出“这是一段文字中的粗体”
$(“#test”).html();//输出“这是一段文字中的<b>粗体</b>”
$(“#input”).val();//输出“文本值”
$(“#a”).attr(“href”);//输出“http://...”, 获取元素属性值

Set text attribute value:

js code:

$(“#test”).text('');
$(“#test”).html('');
$(“#input”).val('');
$(“#a”).attr('href','xxx');

Add element:

$(“#test”).append(“<span>添加文本</span>”;//在id=test的标签末尾添加这段代码
$(“#test”).prepend(“<span>添加文本</span>”;//在被选标签的开头添加这段代码
$(“#test”).after(“<span>添加文本</span>”;//在被选标签之后添加这段代码
$(“#test”).before(“<span>添加文本</span>”;//在被选 标签之前添加这段代码

Delete element:

$(“#div1”).remove();//删除被选元素及其所有的子元素
$(“#div1”).empty();//删除被选元素的所有子元素
$(“#div1”).remove(“.info”);//删除被选元素的类名为info的子元素

Find element:

$("#test").parent(); //返回被选元素的直接父级元素(只是一个);
$("#test").parents(); //返回被选元素所有的祖先元素;
$("#test").children(空/选择器);//值为空时返回被选元素的所有直接子元素(很多),为选择器时返回特定子元素(只是一个);
$("#test").find('.aaa'); //在test元素下寻找类名为aaa的元素
$("#test").next(); //返回被选元素的下一个同胞元素(只一个);

Operation css:

addClass/removeClass(“…”);//向元素添加/删除类名
$(“p”).css(“color”);//返回p元素的color样式属性的值
$(“p”).css(“color”,”red”);//把p元素的color属性设为red
$(“p”).css({“color”:””red”, “font-size”:”14px”});//同时给p设置多个属性值

jQuery AJAX:

jquery ajax function

I encapsulated an ajax function myself, the code is as follows:

var Ajax = function(url, success) {
$.ajax({
url: url,
type: 'get',
dataType: 'json',
timeout: 10000,
success: function(d) {
var data = d.data;
success && success(data);
},
error: function(e) {
throw new Error(e);
}
});
};
// 使用方法:
Ajax('/data.json', function(data) {
console.log(data);
});

jsonp:

Sometimes we need to use the jsonp method in order to cross domains. I also encapsulated a function:

function jsonp(config) {
var options = config || {}; // 需要配置url, success, time, fail四个属性
var callbackName = ('jsonp_' + Math.random()).replace(".", "");
var oHead = document.getElementsByTagName('head')[0];
var oScript = document.createElement('script');
oHead.appendChild(oScript);
window[callbackName] = function(json) { //创建jsonp回调函数
oHead.removeChild(oScript);
clearTimeout(oScript.timer);
window[callbackName] = null;
options.success && options.success(json); //先删除script标签,实际上执行的是success函数
};
oScript.src = options.url + '&#63;' + callbackName; //发送请求
if (options.time) { //设置超时处理
oScript.timer = setTimeout(function () {
window[callbackName] = null;
oHead.removeChild(oScript);
options.fail && options.fail({ message: "超时" });
}, options.time);
}
};
// 使用方法:
jsonp({
url: '/b.com/b.json',
success: function(d){
//数据处理
},
time: 5000,
fail: function(){
//错误处理
} 
});

Encapsulated common functions

$(window).scroll(function() {
var a = $(window).scrollTop();
if(a > 100) {
$('.go-top').fadeIn();
}else {
$('.go-top').fadeOut();
}
});
$(".go-top").click(function(){
$("html,body").animate({scrollTop:"0px"},'600');
});

Block bubbling function

function stopBubble(e){
e = e || window.event; 
if(e.stopPropagation){ 
e.stopPropagation(); //W3C阻止冒泡方法 
}else { 
e.cancelBubble = true; //IE阻止冒泡方法 
} 
}

Get the object attribute value after "?" in the url

var getURLParam = function(name) {
return decodeURIComponent((new RegExp('[&#63;|&]' + name + '=' + '([^&;]+&#63;)(&|#|;|$)', "ig").exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;
};

Deep copy object

function cloneObj(obj) {
var o = obj.constructor == Object &#63; new obj.constructor() : new obj.constructor(obj.valueOf());
for(var key in obj){
if(o[key] != obj[key] ){
if(typeof(obj[key]) == 'object' ){
o[key] = mods.cloneObj(obj[key]);
}else{
o[key] = obj[key];
}
}
}
return o;
}

Generate random numbers

function randombetween(min,max){
return min + (Math.random() * (max-min +1));
}
console.log(parseInt(randombetween(50,100)));

Others

Git common commands

1、git config user.name \ user.email //查看当前git的用户名称、邮箱
2、git clone https://github.com/jarson7426/javascript.git //clone仓库到本地。
3、修改本地代码,提交到分支: git add file \ git commit -m “新增文件”
4、把本地库推送到远程库: git push origin master
5、查看提交日志:git log -5
6、返回某一个版本:git reset --hard 123
7、创建分支:git branch name \ git checkout name
8、合并name分支到当前分支:git merge name
9、删除本地分支:git branch -d name
10、删除远程分支: git push origin :daily/x.x.x
11、git checkout -b mydev origin/daily/1.0.0 //把远程daily分支映射到本地mydev分支进行开发
12、合并远程分支到当前分支 git pull origin daily/1.1.1
13、发布到线上:
git tag publish/0.1.5
git push origin publish/0.1.5:publish/0.1.5

The above content is a summary of the common knowledge points of jQuery introduced by the editor and the commonly used encapsulation functions. I hope it will be helpful to everyone!

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
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools