Home > Web Front-end > JS Tutorial > jQuery Basics Learning Guide_jquery

jQuery Basics Learning Guide_jquery

WBOY
Release: 2016-05-16 15:45:00
Original
862 people have browsed it

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!');
});

Copy after login

Also, it has a shorthand

$(function() {
  console.log('ready!');
});

Copy after login

$(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);

Copy after login

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

Copy after login

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, is an exception. jQuery will determine whether the element is visible based on the display attribute in the CSS of the element.

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>&#63;
  return width === 0 && height === 0 && !skip &#63;

    // then it must be hidden
    true :

    // but if it has width and height
    // and it's not a <tr>
    width > 0 && height > 0 && !skip &#63;

      // 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 );
};

Copy after login

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')) { ... }

Copy after login

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) { ... }

Copy after login

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');

Copy after login

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);        // 第六个

Copy after login

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'); // 选择所有可输入的表单元素

Copy after login

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!');

Copy after login

For chained operations, it is important to keep the code readable:

$('#content')
  .find('h3')
  .eq(2)
  .html('new text for the third h3!');

Copy after login

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!');

Copy after login

链式操作非常好用,以至于现在很多其它 JavaScript 库都加入了类似特性。但是对于链式操作也要小心使用,过长的链式操作会给代码的修改和调试带来困难。对于链式操作的长度没有硬性规定 — 只要你觉得能 Hold 住。

jQuery 对有些方法进行了“重载”,所有对某元素赋值或取值的时候所用的方法名是一样的,只是参数列表不同。当用 jQuery 方法对元素赋值的时候,它称为 setter,取值的时候称为 getter。setter 会对选择器中的所有所有元素赋值,getter 只取得选择器中第一个元素的值。

$('h1').html('hello world'); // setter
var str = $('h1').html();  // getter

Copy after login

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' }); // 给多个属性赋值

Copy after login

上面可以看到,一次性给多个属性赋值的时候,实际上传入的是一个对象,这个对象中包含了一些可以表示 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')) { ... }

Copy after login

尺寸

jQuery 中有很多方法可以用来获取或者修改元素的尺寸或者位置信息。

$('h1').width('50px');  // 设置所有 h1 元素的宽度
$('h1').width();     // 得到第一个 h1 元素的宽度

$('h1').height('50px'); // 设置所有 h1 元素的高度
$('h1').height();    // 得到第一个 h1 元素的高度

$('h1').position();   // 返回第一个 h1 元素
             // 的位置信息,此返回值是一个对象
             // 此位置是相对其父元素的位置的偏移量

Copy after login

这里只是对 jQuery 操纵元素大小及位置信息的简单举例。


Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template