Open a web page. If the HTML has not been fully loaded, it is unsafe to operate the elements on the page. But what about monitoring whether the HTML has been loaded? jQuery provides a $(document).ready() method. Any code in ready will not be executed until the HTML is completely loaded.
$(document).ready(function() { console.log('ready!'); });
Also, it has a shorthand
$(function() { console.log('ready!'); });
$(document).ready() does not only execute anonymous methods, but also executes a named method:
function readyFn() { // code to run when the document is ready } $(document).ready(readyFn);
Select element
The most basic concept of jQuery is "select some elements and then do something with them". jQuery supports most CSS3 selectors, as well as some non-standard selectors. For details, see http://api.jquery.com/category/selectors/. Here are the usages of some common selectors:
$('#myId'); // 此 ID 在页面中必须唯一 $('div.myClass'); // 如果指定了元素类型,那么性能会有所提升 $('input[name=first_name]'); // 速度有点慢,尽量避免这种用法 $('#contents ul.people li'); $('a.external:first'); $('tr:odd'); $('#myForm :input'); // 选择表单中的所有 input 类元素 $('div:visible'); $('div:gt(2)'); // 页面中除了前 3 个 DIV 之外的所有 DIV $('div:animated'); // 所有正在执行动画的 DIV
Things to note
When using pseudo-selectors such as :visible and :hidden, jQuery actually detects whether they are visible on the page, not the display value in their css. That is to say, when the physical width and height of an element on the page are both greater than 0, then it is visible. However,
For the specific implementation of jQuery, please refer to the code:
jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight, skip = elem.nodeName.toLowerCase() === "tr"; // does the element have 0 height, 0 width, // and it's not a <tr>? return width === 0 && height === 0 && !skip ? // then it must be hidden true : // but if it has width and height // and it's not a <tr> width > 0 && height > 0 && !skip ? // then it must be visible false : // if we get here, the element has width // and height, but it's also a <tr>, // so check its display property to // decide whether it's hidden jQuery.curCSS(elem, "display") === "none"; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); };
Whether the selector result set contains elements
After executing a selector, how to determine whether the selector has selected an element? You may take it for granted and write:
if ($('div.foo')) { ... }
In fact, this is wrong to write, because no matter whether the selector selects an element or not, it will return an object, and the Boolean value of the object must be true, so this method will not work. In fact, there is a length attribute in the object returned by the selector. Through this attribute, you can determine how many elements there are in the selector. If no element is selected, 0-false is returned. If an element is selected, the actual number of elements is returned. number-true.
if ($('div.foo').length) { ... }
Cache the selector
Every time you make a selector, jQuery has to execute a lot of code. If you need to use the same selector multiple times, it is best to cache the selector to avoid executing the selector repeatedly.
var $divs = $('div');
Note that the variable name used as a cache variable in this code starts with $. This dollar sign is just an ordinary character in JavaScript and has no other special meaning. The use of $ here is just a common habit. , not mandatory.
Once the selector is cached in the variable, you can call jQuery methods on the variable, just like calling the selector.
It should also be noted that the selector can only select the elements currently on the page. If elements are added to the page after the selector is executed, the elements added the day after tomorrow are not included in the previous selector. Unless the selector is executed again after adding elements to the page.
Selector with filter function
Sometimes after executing a selector, not all elements in the result set are what we want, so we need to filter the result set again:
$('div.foo').has('p'); // 所有包含有 <p> 的 div.foo $('h1').not('.bar'); // 没有被标记 bar 这个类的 h1 元素 $('ul li').filter('.current'); // 带有类 current 的无序列表 $('ul li').first(); // 无序列表中的第一个元素 $('ul li').eq(5); // 第六个
Select form elements
jQuery provides some pseudo-selectors to select form elements, which are very useful.
- :button select button
- :checkbox select multiple checkbox
- :checked selects the selected form element
- :disabled selects disabled form elements
- :enabled selects enabled form elements
- :file selects form elements with type="file"
- :image selects form elements with type="image"
- … …
$('#myForm :input'); // 选择所有可输入的表单元素
How to use selectors
After executing the selector, you can call the methods in the selector. These methods are divided into two categories: getter and setter. The getter returns the properties of the first element in the result set, and the setter can set the properties of all elements in the result set.
Chain operation
Most methods in the jQuery selector will return the jQuery object itself, so after calling a method, you can continue to call other methods on this method, just like a combo:
$('#content').find('h3').eq(2).html('new text for the third h3!');
For chained operations, it is important to keep the code readable:
$('#content') .find('h3') .eq(2) .html('new text for the third h3!');
If the elements in the selector change during the chain operation, you can use the $.fn.end method to return to the original result set:
$('#content') .find('h3') .eq(2) .html('new text for the third h3!') .end() // 返回最初的结果集 .eq(0) .html('new text for the first h3!');
链式操作非常好用,以至于现在很多其它 JavaScript 库都加入了类似特性。但是对于链式操作也要小心使用,过长的链式操作会给代码的修改和调试带来困难。对于链式操作的长度没有硬性规定 — 只要你觉得能 Hold 住。
jQuery 对有些方法进行了“重载”,所有对某元素赋值或取值的时候所用的方法名是一样的,只是参数列表不同。当用 jQuery 方法对元素赋值的时候,它称为 setter,取值的时候称为 getter。setter 会对选择器中的所有所有元素赋值,getter 只取得选择器中第一个元素的值。
$('h1').html('hello world'); // setter var str = $('h1').html(); // getter
setter 返回的是 jQuery 对象,可以继续在这个对象上调用 jQuery 方法(链式操作),getter 仅放回我们想要的值,返回值不是 jQuery 对象,所以不能继续链式操作了。
jQuery 操作 CSS
jQuery 可以很方便的设置或取得元素的 CSS 属性。
CSS 属性如果要想在 JavaScript 中使用,多要转换成骆驼命名法(camel cased),例如 CSS 中的 font-size 属性,在 JavaScript 中对应的是 fontSize,但是 jQuery 的 $.fn.css 方法对此做了特殊处理,无论使用哪种写法都可以。
例如:
var strsize1 = $('h1').css('fontSize'); // 返回 "19px" var strsize2 = $('h1').css('font-size'); // 同上 $('h1').css('fontSize', '100px'); // 给单个属性赋值 $('h1').css({ 'fontSize' : '100px', 'color' : 'red' }); // 给多个属性赋值
上面可以看到,一次性给多个属性赋值的时候,实际上传入的是一个对象,这个对象中包含了一些可以表示 CSS 属性的键-值对,在 jQuery 的很多 setter 方法中都有类似用法。
jQuery 操作元素的 class 属性
作为一个 getter,$.fn.css 确实很好用,但是应该尽量避免将其作为 setter 使用,因为一般不建议在 JavaScript 代码中包含太多的样式代码。比较靠谱的方法是把样式规则单独分开写成类(class),然后用 JavaScript 将类应用到元素上即可:
var $h1 = $('h1'); $h1.addClass('big'); $h1.removeClass('big'); $h1.toggleClass('big'); if ($h1.hasClass('big')) { ... }
尺寸
jQuery 中有很多方法可以用来获取或者修改元素的尺寸或者位置信息。
$('h1').width('50px'); // 设置所有 h1 元素的宽度 $('h1').width(); // 得到第一个 h1 元素的宽度 $('h1').height('50px'); // 设置所有 h1 元素的高度 $('h1').height(); // 得到第一个 h1 元素的高度 $('h1').position(); // 返回第一个 h1 元素 // 的位置信息,此返回值是一个对象 // 此位置是相对其父元素的位置的偏移量
这里只是对 jQuery 操纵元素大小及位置信息的简单举例。

实现方法:1、用“$("img").delay(毫秒数).fadeOut()”语句,delay()设置延迟秒数;2、用“setTimeout(function(){ $("img").hide(); },毫秒值);”语句,通过定时器来延迟。

区别:1、axios是一个异步请求框架,用于封装底层的XMLHttpRequest,而jquery是一个JavaScript库,只是顺便封装了dom操作;2、axios是基于承诺对象的,可以用承诺对象中的方法,而jquery不基于承诺对象。

修改方法:1、用css()设置新样式,语法“$(元素).css("min-height","新值")”;2、用attr(),通过设置style属性来添加新样式,语法“$(元素).attr("style","min-height:新值")”。

增加元素的方法:1、用append(),语法“$("body").append(新元素)”,可向body内部的末尾处增加元素;2、用prepend(),语法“$("body").prepend(新元素)”,可向body内部的开始处增加元素。

删除方法:1、用empty(),语法“$("div").empty();”,可删除所有子节点和内容;2、用children()和remove(),语法“$("div").children().remove();”,只删除子元素,不删除内容。

在jquery中,apply()方法用于改变this指向,使用另一个对象替换当前对象,是应用某一对象的一个方法,语法为“apply(thisobj,[argarray])”;参数argarray表示的是以数组的形式进行传递。

on()方法有4个参数:1、第一个参数不可省略,规定要从被选元素添加的一个或多个事件或命名空间;2、第二个参数可省略,规定元素的事件处理程序;3、第三个参数可省略,规定传递到函数的额外数据;4、第四个参数可省略,规定当事件发生时运行的函数。

去掉方法:1、用“$(selector).removeAttr("readonly")”语句删除readonly属性;2、用“$(selector).attr("readonly",false)”将readonly属性的值设置为false。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools
