search
HomeWeb Front-endJS TutorialSummary of jQuery common operation methods and commonly used functions_jquery

An article about jQuery’s common methods and functions to keep as a memo.

JQuery common operation implementation methods

$("Tag name") //Get html elements document.getElementsByTagName("")

$("#ID") //Get a single control document.getElementById("")

$("div #ID") //Get the control in a certain control

$("#ID #ID") // Get the control through the control ID

$("label.class style name") //Get the control through class

$("#ID").val(); //Get value

$("#ID").val(""); //Assign value

$("#ID").hide(); //Hide

$("#ID").show(); //Show

$("#ID").text(); //Equivalent to taking innerText

$("#ID").text(""); //Equivalent to innerText=""

$("#ID").html(); //Equivalent to taking innerHTML

$("#ID").html(""); //Equivalent to innerHTML=""

$("#ID").css("property","value") //Add CSS style

$("form#form id").find("#the control id found").end() //Traverse the form

$("#ID").load("*.html") //Load a file

For example:

$("form#frmMain").find("#ne").css("border", "1px solid #0f0").end() // end()返回表单

.find("#chenes").css("border-top","3px dotted #00f").end()

$.ajax({ url: "Result.aspx", //数据请求页面的url

type:"get", //数据传递方式(get或post)

dataType:"html", //期待数据返回的数据格式(例如 "xml", "html", "script",或 "json")

data: "chen=h", //传递数据的参数字符串,只适合get方式

timeout:3000, //设置时间延迟请求的时间

success:function(msg)//当请求成功时触发函数
{
$("#stats").text(msg);
},
error:function(msg) //当请求失败时触发的函数
{
$("#stats").text(msg);
}
});

$(document).ready(function(){});
$("#description").mouseover(function(){});

//ajax方法

$.get( "Result.aspx", //数据请求页面的url
{ chen: "测试",age:"25"}, //传递数据的参数字符串
function(data){ alert("Data Loaded: " + data); } //触发后的函数
);
});
});

//取得下拉选单的选取值

$(#testSelect option:selected').text(); //取文本值
或$("#testSelect").find('option:selected').text();
或$("#testSelect").val();

------

Summary of commonly used function methods in jQuery

Event handling

ready(fn)

Code:

$(document).ready(function(){
// Your code here...
});

Function: It can greatly improve the response speed of web applications. By using this method, you can call the function you bound as soon as the DOM is loaded and ready to be read and manipulated, and 99.99% of JavaScript functions need to be executed at that moment.

bind(type,[data],fn)

Code:

$("p").bind("click", function(){
alert( $(this).text() );
});

Function: Bind an event handler function to a specific event (like click) of each matching element. Plays the role of event monitoring.

toggle(fn,fn)
Code:

$("td").toggle(
function () {
$(this).addClass("selected");
},
function () {
$(this).removeClass("selected");
}
);

Function: Switch the function to be called every time you click. If a matching element is clicked, the first function specified is triggered, and when the same element is clicked again, the second function specified is triggered. It's a very interesting function that may be used when dynamically implementing certain functions.

(Events like click(), focus(), keydown() will not be mentioned here, they are commonly used in development.)

Appearance

addClass(class) and removeClass(class)

Code:

$(".stripe tr").mouseover(function(){ 
$(this).addClass("over");}).mouseout(function(){
$(this).removeClass("over");})
});

can also be written as:

$(".stripe tr").mouseover(function() { $(this).addClass("over") });
$(".stripe tr").mouseout(function() { $(this).removeClass("over") });

Function: Add or remove styles for specified elements to achieve dynamic style effects. In the above example, the code for moving a two-color table with the mouse is implemented.

css(name,value)

Code:
$("p").css("color","red");

Function: Very simple, it is to set the value of a style attribute in the matched element. This personal feeling is somewhat similar to addClass(class) above.

slide(),hide(),fadeIn(), fadeout(), slideUp() ,slideDown()

Code:

$("#btnShow").bind("click",function(event){ $("#divMsg").show() });
$("#btnHide").bind("click",function(evnet){ $("#divMsg").hide() });

Function: Several commonly used dynamic effect functions provided in jQuery. You can also add parameters: show(speed,[callback]) to display all matching elements in an elegant animation and optionally trigger a callback function after the display is completed.

animate(params[,duration[,easing[,callback]]])

Function: The function used to create animation effects is very powerful and can be used continuously.

Search and filter

map(callback)
HTML code:

<p><b>Values: </b></p>
<form>
<input type="text" name="name" value="John"/>
<input type="text" name="password" value="password"/>
<input type="text" name="url" value="http://www.fufuok.com/>
</form>

jQuery code:

$("p").append( $("input").map(function(){
return $(this).val();
}).get().join(", ") );

结果:
[

John, password, http://www.fufuok.com/

]

作用:将一组元素转换成其他数组(不论是否是元素数组)你可以用这个函数来建立一个列表,不论是值、属性还是CSS样式,或者其他特别形式。这都可以用'$.map()'来方便的建立。

find(expr)

HTML 代码:

Hello, how are you?


jQuery 代码:

$("p").find("span")
结果:

[ Hello ]

作用:搜索所有与指定表达式匹配的元素。这个函数是找出正在处理的元素的后代元素的好方法。

文档处理

attr(key,value)
HTML 代码:
Summary of jQuery common operation methods and commonly used functions_jquerySummary of jQuery common operation methods and commonly used functions_jquery
jQuery 代码:
$("img").attr("src","test.jpg");

作用:取得或设置匹配元素的属性值。通过这个方法可以方便地从第一个匹配元素中获取一个属性的值。如果元素没有相应属性,则返回 undefined 。在控制HTML标记上是必备的工具。

html()/html(val)
HTML 代码:

Hello


jQuery 代码:
$("div").html();
结果:

Hello

作用:取得或设置匹配元素的html内容,同类型的方法还有text()和val()。前者是取得所有匹配元素的内容。,后者是获得匹配元素的当前值。三者有相似的地方常用在内容的操作上。

wrap(html)
HTML 代码:

Test Paragraph.


jQuery 代码:
$("p").wrap("
");
结果:

Test Paragraph.

作用:把所有匹配的元素用其他元素的结构化标记包裹起来。
这种包装对于在文档中插入额外的结构化标记最有用,而且它不会破坏原始文档的语义品质。 可以灵活的修改我们的DOM。

empty()
HTML 代码:

Hello, Person and person


jQuery 代码:
$("p").empty();
结果:

作用:删除匹配的元素集合中所有的子节点。

Ajax处理

load(url,[data],[callback])
url (String) : 待装入 HTML 网页网址。
data (Map) : (可选) 发送至服务器的 key/value 数据。
callback (Callback) : (可选) 载入成功时回调函数。

代码:

$("#feeds").load("feeds.aspx", {limit: 25}, function(){
alert("The last 25 entries in the feed have been loaded");
});

作用:载入远程 HTML 文件代码并插入至 DOM 中。这也是Jquery操作Ajax最常用最有效的方法。

serialize()
HTML 代码:

<p id="results"><b>Results: </b> </p>
<form>
<select name="single">
<option>Single</option>
<option>Single2</option>
</select>
<select name="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select><br/>
<input type="checkbox" name="check" value="check1"/> check1
<input type="checkbox" name="check" value="check2"
checked="checked"/> check2
<input type="radio" name="radio" value="radio1"
checked="checked"/> radio1
<input type="radio" name="radio" value="radio2"/> radio2
</form>

jQuery 代码:

$("#results").append( "<tt>" + $("form").serialize() + "</tt>" );

作用:序列化表格内容为字符串。用于 Ajax 请求。

工具

jQuery.each(obj,callback)

代码:

$.each( [0,1,2], function(i, n){
alert( "Item #" + i + ": " + n );
});//遍历数组
$.each( { name: "John", lang: "JS" }, function(i, n){
alert( "Name: " + i + ", Value: " + n );//遍历对象
});

作用:通用例遍方法,可用于例遍对象和数组。

jQuery.makeArray(obj)
HTML 代码:

<div>First</div><div>Second</div><div>Third</div><div>Fourth</div>


jQuery 代码:

var arr = jQuery.makeArray(document.getElementsByTagName("div"));

结果:
Fourth
Third
Second
First

作用:将类数组对象转换为数组对象。使我们可以在数组和对象之间灵活的转换。

jQuery.trim(str)

作用:这个大家应该很熟悉,就是去掉字符串起始和结尾的空格。

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: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

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.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

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: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

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.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

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

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

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.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

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.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development 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),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor