search
HomeWeb Front-endJS TutorialjQuery syntax summary (super practical)

jQuery syntax summary (super practical)

May 16, 2016 pm 03:22 PM
jquerygrammar

1、關於頁元素的引用

透過jquery的$()引用元素包括透過id、class、元素名稱以及元素的層級關係及dom或xpath條件等方法,且傳回的物件為jquery物件(集合物件),不能直接呼叫dom定義的方法。

2、jQuery物件與dom物件的轉換

只有jquery物件才能使用jquery定義的方法。注意dom物件和jquery物件是有差別的,呼叫方法時要注意操作的是dom物件還是jquery物件。

普通的dom物件一般可以透過$()轉換成jquery物件。

如:$(document.getElementById("msg"))則為jquery對象,可以使用jquery的方法。

由於jquery物件本身就是一個集合。所以如果jquery物件要轉換為dom物件則必須取出其中的某一項,一般可透過索引取出。

如:$("#msg")[0],$("div").eq(1)[0],$("div").get()[1] ,$("td")[5]這些都是dom對象,可以使用dom中的方法,但不能再使用Jquery的方法。

以下幾種寫法都是正確的:

程式碼

$("#msg").html();
$("#msg")[0].innerHTML;
$("#msg").eq(0)[0].innerHTML;
$("#msg").get(0).innerHTML;


對於取得的元素集合,取得其中的某一項(透過索引指定)可以使用eq或get(n)方法或索引號取得,要注意,eq回傳的是jquery對象,而get(n)和索引傳回的是dom元素物件。對於jquery物件只能使用jquery的方法,而dom物件只能使用dom的方法,如要取得第三個
元素的內容。有以下兩種方法:


程式碼
$("div").eq(2).html(); //调用jquery对象的方法
$("div").get(2).innerHTML; //调用dom的方法属性

4、相同函數實作和get


Jquery中的許多方法都是如此,主要包括以下幾個:


$("#msg").html(); //返回id為msg的元素節點的html內容。 $("#msg").html("new content
"); //將「new content
」 以html字串寫入id為msg的字串元素節點內容中,頁顯示粗體的new content
$("#msg").text(); //傳回id為msg的元素節點的文字內容。 $("#msg").text("new content
"); //將「new content」 作為普通文字字串寫入id為msg的元素節點內容中,頁顯示new content

$("#msg").height(); //傳回id為msg的元素的高度
$("#msg" ).height(""); //將id為msg的元素的高度設為
$("#msg").width(); //傳回id為msg的元素的寬度
$( "#msg").width(""); //將id為msg的元素的寬度設為
$("input").val("); //傳回表單輸入框的value值
$("input").val("test"); //將表單輸入框的value值設為test
$("#msg").click(); //觸發id為msg的元素的點選事件

$("#msg").click(fn); //為id為msg的元素點選事件新增函數

同樣blur,focus,select,submit事件都可以有著兩種呼叫方法

5、集合處理功能


對於jquery返回的集合內容無需我們自己循環遍歷並對每個物件分別做處理,jquery已經為我們提供的很方便的方法進行集合的處理。


6、擴充我們需要的功能


程式碼
$("p").each(function(i){this.style.color=['#f00','#0f0','#00f'][i]}) 
//为索引分别为0,1,2的p元素分别设定不同的字体颜色。
$("tr").each(function(i){this.style.backgroundColor=['#ccc','#fff'][i%2]}) 
//实现表格的隔行换色效果
$("p").click(function(){alert($(this).html())}) 
//为每个p元素增加了click事件,单击某个p元素则弹出其内容


使用擴充的方法(以「$.方法名稱」呼叫):

alert("a=10,b=20,max="+$.max(10,20)+",min="+$ .min(10,20));

7、支援方法的連寫
$.extend({
min: function(a, b){return a < b?a:b; },
max: function(a, b){return a > b?a:b; } 
}); //为jquery扩展了min,max两个方法 http://www.cnblogs.com/sosoft/

所謂連寫,即可以對一個jquery物件連續呼叫各種不同的方法。

例如:

8、操作元素的样式

主要包括以下几种方式:

$("#msg").css("background"); //返回元素的背景颜色
$("#msg").css("background","#ccc") //设定元素背景为灰色
$("#msg").height(); $("#msg").width(""); //设定宽高
$("#msg").css({ color: "red", background: "blue" });//以名值对的形式设定样式
$("#msg").addClass("select"); //为元素增加名称为select的class
$("#msg").removeClass("select"); //删除元素名称为select的class
$("#msg").toggleClass("select"); //如果存在(不存在)就删除(添加)名称为select的class

9、完善的事件处理功能

Jquery已经为我们提供了各种事件处理方法,我们无需在html元素上直接写事件,而可以直接为通过jquery获取的对象添加事件。
如:

$("#msg").click(function(){alert("good")}) //为元素添加了单击事件
$("p").click(function(i){this.style.color=[&#39;#f00&#39;,&#39;#0f0&#39;,&#39;#00f&#39;][i]})
//为三个不同的p元素单击事件分别设定不同的处理

jQuery中几个自定义的事件:

(1)hover(fn1,fn2):一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法。当鼠标移动到一个匹配的元素上面时,会触发指定的第一个函数。当鼠标移出这个元素时,会触发指定的第二个函数。
//当鼠标放在表格的某行上时将class置为over,离开时置为out。

$("tr").hover(function(){
$(this).addClass("over");
},
function(){
$(this).addClass("out"); 
});

(2)ready(fn):当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。

$(document).ready(function(){alert("Load Success")})
//页面加载完毕提示“Load Success”,相当于onload事件。

与$(fn)等价

(3)toggle(evenFn,oddFn): 每次点击时切换要调用的函数。如果点击了一个匹配的元素,则触发指定的第一个函数,当再次点击同一元素时,则触发指定的第二个函数。随后的每次点击都重复对这两个函数的轮番调用。
//每次点击时轮换添加和删除名为selected的class。

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

(4)trigger(eventtype): 在每一个匹配的元素上触发某类事件。

例如:

$("p").trigger("click"); //触发所有p元素的click事件

(5)bind(eventtype,fn),unbind(eventtype): 事件的绑定与反绑定
从每一个匹配的元素中(添加)删除绑定的事件。

例如:

$("p").bind("click", function(){alert($(this).text());}); //为每个p元素添加单击事件
$("p").unbind(); //删除所有p元素上的所有事件
$("p").unbind("click") //删除所有p元素上的单击事件

10、几个实用特效功能

其中toggle()和slidetoggle()方法提供了状态切换功能。
如toggle()方法包括了hide()和show()方法。
slideToggle()方法包括了slideDown()和slideUp方法。

11、几个有用的jQuery方法

$.browser.浏览器类型:检测浏览器类型。有效参数:safari, opera, msie, mozilla。如检测是否ie:$.browser.isie,是ie浏览器则返回true。
$.each(obj, fn):通用的迭代函数。可用于近似地迭代对象和数组(代替循环)。

$.each( [0,1,2], function(i, n){ alert( "Item #" + i + ": " + n ); });

等价于:

var tempArr=[0,1,2];
for(var i=0;i<tempArr.length;i++){
alert("Item #"+i+": "+tempArr[i]);
}

也可以处理json数据,如

$.each( { name: "John", lang: "JS" }, function(i, n){ alert( "Name: " + i + ", Value: " + n ); });

结果为:

Name:name, Value:John
Name:lang, Value:JS
$.extend(target,prop1,propN):用一个或多个其他对象来扩展一个对象,返回这个被扩展的对象。这是jquery实现的继承方式。

如:

$.extend(settings, options);
//合并settings和options,并将合并结果返回settings中,相当于options继承setting并将继承结果保存在setting中。
var settings = $.extend({}, defaults, options);
//合并defaults和options,并将合并结果返回到setting中而不覆盖default内容。
可以有多个参数(合并多项并返回)

$.map(array, fn):数组映射。把一个数组中的项目(处理转换后)保存到到另一个新数组中,并返回生成的新数组。

如:
var tempArr=$.map( [0,1,2], function(i){ return i + 4; });
tempArr内容为:[4,5,6]
var tempArr=$.map( [0,1,2], function(i){ return i > 0 ? i + 1 : null; });
tempArr内容为:[2,3]
$.merge(arr1,arr2):合并两个数组并删除其中重复的项目。
如:$.merge( [0,1,2], [2,3,4] ) //返回[0,1,2,3,4]
$.trim(str):删除字符串两端的空白字符。

如:$.trim(" hello, how are you? "); //返回"hello,how are you? "

12、解决自定义方法或其他类库与jQuery的冲突

  很多时候我们自己定义了$(id)方法来获取一个元素,或者其他的一些js类库如prototype也都定义了$方法,如果同时把这些内容放在一起就会引起变量方法定义冲突,Jquery对此专门提供了方法用于解决此问题。
  使用jquery中的jQuery.noConflict();方法即可把变量$的控制权让渡给第一个实现它的那个库或之前自定义的$方法。之后应用Jquery的时候只要将所有的$换成jQuery即可,如原来引用对象方法$("#msg")改为jQuery("#msg")。

如:

jQuery.noConflict(); 
// 开始使用jQuery
jQuery("div p").hide();
// 使用其他库的 $() 
$("content").style.display = &#39;none&#39;;

以上内容给大家介绍了jQuery语法小结,希望对大家学习jquery相关知识有所帮助。

【相关教程推荐】

1. JavaScript视频教程
2. JavaScript在线手册
3. bootstrap教程

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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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.

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 Tools

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor