麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 編程 > JavaScript > 正文

了解了這些才能開始發揮jQuery的威力

2019-11-20 21:54:28
字體:
來源:轉載
供稿:網友

由于當前jQuery如此的如雷貫耳,相信不用介紹什么是jQuery了,公司代碼中廣泛應用了jQuery,但我在看一些小朋友的代碼時發現一個問題,小朋友們使用的僅僅是jQuery的皮毛,只是使用id選擇器與attr方法,還有幾個動畫,如果只是如此,相比于其帶來的開銷,其實還不如不使用,下面介紹幾個jQuery常用的方法,來讓jQuery的威力發揮出來,否則只用有限的幾個方法,相對于運行速度問題,真不如不用jQuery。

jQuery如此之好用,和其在獲取對象時使用與CSS選擇器兼容的語法有很大關系,畢竟CSS選擇器大家都很熟悉(關于CSS選擇器可以看看十分鐘搞定CSS選擇器),但其強大在兼容了CSS3的選擇器,甚至多出了很多。

選擇器

有了CSS選擇器基礎后,看jQuery的選擇器就很簡單了,不再詳細一一說明

基本選擇器 
$(‘*')匹配頁面所有元素
$(‘#id')id選擇器
$(‘.class')類選擇器
$(‘element')標簽選擇器
  
組合/層次選擇器 
$(‘E,F')多元素選擇器,用”,分隔,同時匹配元素E或元素F
$(‘E F')后代選擇器,用空格分隔,匹配E元素所有的后代(不只是子元素、子元素向下遞歸)元素F
$(E>F)子元素選擇器,用”>”分隔,匹配E元素的所有直接子元素
$(‘E+F')直接相鄰選擇器,匹配E元素之后相鄰同級元素F
$(‘E~F')普通相鄰選擇器(弟弟選擇器),匹配E元素之后同級元素F(無論直接相鄰與否)
$(‘.class1.class2')匹配類名中既包含class1又包含class2的元素
基本過濾選擇器 
$("E:first")所有E中的第一個
$("E:last")所有E中的最后一個
$("E:not(selector)")按照selector過濾E
$("E:even")            所有E中index是偶數
$("E:odd")             所有E中index是奇數
$("E:eq(n)")          所有E中index為n的元素
$("E:gt(n)")          所有E中index大于n的元素
$("E:ll(n)")           所有E中index小于n的元素
$(":header")選擇h1~h7 元素
$("div:animated")選擇正在執行動畫效果的元素
內容過濾器 
$(‘E:contains(value)')內容中包含value值的元素
$(‘E:empty')內容為空的元素
$(‘E:has(F)')子元素中有F的元素,$(‘div:has(a)'):包含a標簽的div
$(‘E: parent')父元素是E的元素,$(‘td: parent'):父元素是td的元素
可視化選擇器 
$(‘E:hidden')所有被隱藏的E
$(‘E:visible')所有可見的E
屬性過濾選擇器 
$(‘E[attr]')含有屬性attr的E
$(‘E[attr=value]')屬性attr=value的E
$(‘E[attr !=value]')屬性attr!=value的E
$(‘E[attr ^=value]')屬性attr以value開頭的E
$(‘E[attr $=value]')屬性attr以value結尾的E
$(‘E[attr *=value]')屬性attr包含value的E
$(‘E[attr][attr *=value]')可以連用
子元素過濾器 
$(‘E:nth-child(n)')E的第n個子節點
$(‘E:nth-child(3n+1)')E的index符合3n+1表達式的子節點
$(‘E:nth-child(even)')E的index為偶數的子節點
$(‘E:nth-child(odd)')E的index為奇數的子節點
$(‘E:first-clild')所有E的第一個子節點
$(‘E:last-clild')所有E的最后一個子節點
$(‘E:only-clild')只有唯一子節點的E的子節點
表單元素選擇器 
$(‘E:type')特定類型的input
$(‘:checked')被選中的checkbox或radio
$(‘option: selected')被選中的option

篩選方法

.find(selector) 查找集合每個元素的子節點

Get the descendants(子節點) of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

復制代碼 代碼如下:
$('li.item-ii').find('li').css('background-color', 'red');

.filter(selector) 過濾當前集合內元素

Reduce(減少) the set of matched elements to those that match the selector or pass the function's test.

復制代碼 代碼如下:
$('li').filter(':even').css('background-color', 'red');

基本方法

.ready(handler) 文檔加載完成后執行的方法,區別于window.onload

Specify a function to execute when the DOM is fully loaded.

復制代碼 代碼如下:

$(document).ready(function() {
  // Handler for .ready() called.
});

.each(function(index,element)) 遍歷集合內每個元素

Iterate over a jQuery object, executing a function for each matched element.

復制代碼 代碼如下:

$("li" ).each(function( index ) {
  console.log( index + ": " + $(this).text() );
});

jQuery.extend( target [, object1 ] [, objectN ] ) 合并對象

Merge the contents of two or more objects together into the first object.

復制代碼 代碼如下:
var object = $.extend({}, object1, object2);

獲取元素

.eq(index) 按index獲取jQuery對象集合中的某個特定jQuery對象

Reduce the set of matched elements to the one at the specified index.

.eq(-index) 按逆序index獲取jQuery對象集合中的某個特定jQuery對象

An integer indicating the position of the element, counting backwards from the last element in the set.

復制代碼 代碼如下:
$( "li" ).eq( 2 ).css( "background-color", "red" );

 

.get(index) 獲取jQuery集合對象中某個特定index的DOM對象(將jQuery對象自動轉換為DOM對象)

Retrieve one of the DOM elements matched by the jQuery object.

復制代碼 代碼如下:
console.log( $( "li" ).get( -1 ) );

.get() 將jQuery集合對象轉換為DOM集合對象并返回

Retrieve the DOM elements matched by the jQuery object.

復制代碼 代碼如下:
console.log( $( "li" ).get() );


.index() / .index(selector)/ .index(element) 從給定集合中查找特定元素index

Search for a given element from among the matched elements.

1. 沒參數返回第一個元素index

2.如果參數是DOM對象或者jQuery對象,則返回參數在集合中的index

3.如果參數是選擇器,返回第一個匹配元素index,沒有找到返回-1

復制代碼 代碼如下:

var listItem = $( "#bar" );
alert( "Index: " + $( "li" ).index( listItem ) );

.clone([withDataAndEvents][,deepWithDataAndEvents]) 創建jQuery集合的一份deep copy(子元素也會被復制),默認不copy對象的shuju和綁定事件

Create a deep copy of the set of matched elements.

復制代碼 代碼如下:
$( ".hello" ).clone().appendTo( ".goodbye" );

.parent([selector]) 獲取jQuery對象符合selector的父元素

Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

復制代碼 代碼如下:
$( "li.item-a" ).parent('ul').css( "background-color", "red" );

.parents([selector]) 獲取jQuery對象符合選擇器的祖先元素

Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.

復制代碼 代碼如下:
$( "span.selected" ) .parents( "div" ) .css( "border", "2px red solid" )

插入元素

.append(content[,content]) / .append(function(index,html)) 向對象尾部追加內容

Insert content, specified by the parameter, to the end of each element in the set of matched elements.

1. 可以一次添加多個內容,內容可以是DOM對象、HTML string、 jQuery對象

2. 如果參數是function,function可以返回DOM對象、HTML string、 jQuery對象,參數是集合中的元素位置與原來的html值

復制代碼 代碼如下:

$( ".inner" ).append( "<p>Test</p>" );
$( "body" ).append( $newdiv1, [ newdiv2, existingdiv1 ] );
$( "p" ).append( "<strong>Hello</strong>" );
$( "p" ).append( $( "strong" ) );
$( "p" ).append( document.createTextNode( "Hello" ) );

.appendTo(target) 把對象插入到目標元素尾部,目標元素可以是selector, DOM對象, HTML string, 元素集合,jQuery對象;

Insert every element in the set of matched elements to the end of the target.

復制代碼 代碼如下:

$( "h2" ).appendTo( $( ".container" ) );
$( "<p>Test</p>" ).appendTo( ".inner" );

.prepend(content[,content]) / .prepend(function(index,html)) 向對象頭部追加內容,用法和append類似

Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

復制代碼 代碼如下:
$( ".inner" ).prepend( "<p>Test</p>" );

.prependTo(target) 把對象插入到目標元素頭部,用法和prepend類似

Insert every element in the set of matched elements to the beginning of the target.

復制代碼 代碼如下:
$( "<p>Test</p>" ).prependTo( ".inner" );

.before([content][,content]) / .before(function) 在對象前面(不是頭部,而是外面,和對象并列同級)插入內容,參數和append類似

Insert content, specified by the parameter, before each element in the set of matched elements.

復制代碼 代碼如下:

$( ".inner" ).before( "<p>Test</p>" );
$( ".container" ).before( $( "h2" ) );
$( "p" ).first().before( newdiv1, [ newdiv2, existingdiv1 ] );
$( "p" ).before( "<b>Hello</b>" );
$( "p" ).before( document.createTextNode( "Hello" ) );

.insertBefore(target) 把對象插入到target之前(同樣不是頭部,是同級)

Insert every element in the set of matched elements before the target.

復制代碼 代碼如下:
$( "h2" ).insertBefore( $( ".container" ) );

.after([content][,content]) / .after(function(index)) 和before相反,在對象后面(不是尾部,而是外面,和對象并列同級)插入內容,參數和append類似

Insert content, specified by the parameter, after each element in the set of matched elements.

復制代碼 代碼如下:

$( ".inner" ).after( "<p>Test</p>" );
$( "p" ).after( document.createTextNode( "Hello" ) );

.insertAfter(target) 和insertBefore相反,把對象插入到target之后(同樣不是尾部,是同級)

Insert every element in the set of matched elements after the target.

復制代碼 代碼如下:

$( "<p>Test</p>" ).insertAfter( ".inner" );
$( "p" ).insertAfter( "#foo" );

包裹元素

.wrap(wrappingElement) / .wrap(function(index)) 為每個對象包裹一層HTML結構,可以是selector, element, HTML string, jQuery object

Wrap an HTML structure around each element in the set of matched elements.

復制代碼 代碼如下:

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>$( ".inner" ).wrap( "<div class='new'></div>" );
<div class="container">
  <div class="new">
    <div class="inner">Hello</div>
  </div>
  <div class="new">
    <div class="inner">Goodbye</div>
  </div>
</div>

.wrapAll(wrappingElement) 把所有匹配對象包裹在同一個HTML結構中

Wrap an HTML structure around all elements in the set of matched elements.

復制代碼 代碼如下:

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>$( ".inner" ).wrapAll( "<div class='new' />");<div class="container">
  <div class="new">
    <div class="inner">Hello</div>
    <div class="inner">Goodbye</div>
  </div>
</div>

.wrapInner(wrappingElement) / .wrapInner(function(index)) 包裹匹配元素內容,這個不好說,一看例子就懂

Wrap an HTML structure around the content of each element in the set of matched elements.

復制代碼 代碼如下:

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>$( ".inner" ).wrapInner( "<div class='new'></div>");
<div class="container">
  <div class="inner">
    <div class="new">Hello</div>
  </div>
  <div class="inner">
    <div class="new">Goodbye</div>
  </div>
</div>

.unwap() 把DOM元素的parent移除

Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

復制代碼 代碼如下:
pTags = $( "p" ).unwrap();

屬性方法

.val() 獲取元素的value值

Get the current value of the first element in the set of matched elements.

復制代碼 代碼如下:

$( "input:checkbox:checked" ).val();

.val(value) /.val(function(index,value)) 為元素設置值,index和value同樣是指在為集合中每個元素設置的時候該元素的index和原value值

Set the value of each element in the set of matched elements.

復制代碼 代碼如下:

$( "input" ).val( ‘hello' );
$( "input" ).on( "blur", function() {
  $( this ).val(function( i, val ) {
    return val.toUpperCase();
  });
});

.attr(attributeName) 獲取元素特定屬性的值

Get the value of an attribute for the first element in the set of matched elements.

復制代碼 代碼如下:

var title = $( "em" ).attr( "title" );

.attr(attributeName,value) / .attr(attributesJson) / .attr( attributeName, function(index, attr) ) 為元素屬性賦值

Set one or more attributes for the set of matched elements.

復制代碼 代碼如下:

$( "#greatphoto" ).attr( "alt", "Beijing Brush Seller" );

$( "#greatphoto" ).attr({
  alt: "Beijing Brush Seller",
  title: "photo by Kelly Clark"
});

$( "#greatphoto" ).attr( "title", function( i, val ) {
  return val + " - photo by Kelly Clark";
});

.prop( propertyName ) 獲取元素某特性值

Get the value of a property for the first element in the set of matched elements.

復制代碼 代碼如下:

$( elem ).prop( "checked" )

.prop(propertyName,value) / .prop(propertiesJson) / .prop(propertyName,function(index,oldPropertyValue)) 為元素特性賦值

Set one or more properties for the set of matched elements.

復制代碼 代碼如下:

$( "input" ).prop( "checked", true );

$( "input[type='checkbox']" ).prop( "checked", function( i, val ) {
  return !val;
});

$( "input[type='checkbox']" ).prop({
  disabled: true
});

關于attribute 和 property區別可以看看 jQuery的attr與prop


.data(key,value) / .value(json) 為HTML DOM元素添加數據,HTML5元素 已有data-*屬性

Store arbitrary data associated with the matched elements.The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

復制代碼 代碼如下:

$( "body" ).data( "foo", 52 );
$( "body" ).data( "bar", { myType: "test", count: 40 } );
$( "body" ).data( { baz: [ 1, 2, 3 ] } );

.data(key) / .data() 獲取獲取data設置的數據或者HTML5 data-*屬性中的數據

Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.

復制代碼 代碼如下:

alert( $( "body" ).data( "foo" ) );
alert( $( "body" ).data() );

alert( $( "body" ).data( "foo" ) ); // undefined
$( "body" ).data( "bar", "foobar" );
alert( $( "body" ).data( "bar" ) ); // foobar

CSS方法
.hasClass(calssName) 檢查元素是否包含某個class,返回true/false

Determine whether any of the matched elements are assigned the given class.

復制代碼 代碼如下:
$( "#mydiv" ).hasClass( "foo" )

.addClass(className) / .addClass(function(index,currentClass)) 為元素添加class,不是覆蓋原class,是追加,也不會檢查重復

Adds the specified class(es) to each of the set of matched elements.

復制代碼 代碼如下:

$( "p" ).addClass( "myClass yourClass" );

$( "ul li" ).addClass(function( index ) {
  return "item-" + index;
});

removeClass([className]) / ,removeClass(function(index,class)) 移除元素單個/多個/所有class

Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

復制代碼 代碼如下:

$( "p" ).removeClass( "myClass yourClass" );
$( "li:last" ).removeClass(function() {
  return $( this ).prev().attr( "class" );
});

.toggleClass(className) /.toggleClass(className,switch) /  .toggleClass([switch]) / .toggleClass( function(index, class, switch) [, switch ] ) toggle是切換的意思,方法用于切換,switch是個bool類型值,這個看例子就明白

Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

<div class="tumble">Some text.</div>

第一次執行

復制代碼 代碼如下:

$( "div.tumble" ).toggleClass( "bounce" )
<div class="tumble bounce">Some text.</div>

第二次執行

復制代碼 代碼如下:

$( "div.tumble" ).toggleClass( "bounce" )
<div class="tumble">Some text.</div>

復制代碼 代碼如下:

$( "#foo" ).toggleClass( className, addOrRemove );

// 兩種寫法意思一樣

if ( addOrRemove ) {
  $( "#foo" ).addClass( className );
} else {
  $( "#foo" ).removeClass( className );
}

復制代碼 代碼如下:

$( "div.foo" ).toggleClass(function() {
  if ( $( this ).parent().is( ".bar" ) ) {
    return "happy";
  } else {
    return "sad";
  }
});

.css(propertyName) / .css(propertyNames) 獲取元素style特定property的值

Get the value of style properties for the first element in the set of matched elements.

復制代碼 代碼如下:

var color = $( this ).css( "background-color" );

 var styleProps = $( this ).css([
    "width", "height", "color", "background-color"
  ]);

.css(propertyName,value) / .css( propertyName, function(index, value) ) / .css( propertiesJson ) 設置元素style特定property的值

Set one or more CSS properties for the set of matched elements.

復制代碼 代碼如下:

$( "div.example" ).css( "width", function( index ) {
  return index * 50;
});

$( this ).css( "width", "+=200" );


$( this ).css( "background-color", "yellow" );

   $( this ).css({
      "background-color": "yellow",
      "font-weight": "bolder"
    });

事件方法

.bind( eventType [, eventData ], handler(eventObject) ) 綁定事件處理程序,這個經常用,不多解釋

Attach a handler to an event for the elements.

復制代碼 代碼如下:

$( "#foo" ).bind( "click", function() {
  alert( "User clicked on 'foo.'" );
});

.delegate( selector, eventType, handler(eventObject) ) 這個看官方解釋吧

Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

復制代碼 代碼如下:

$( "table" ).on( "click", "td", function() {//這樣把td的click事件處理程序綁在table上
  $( this ).toggleClass( "chosen" );
});

.on( events [, selector ] [, data ], handler(eventObject) ) 1.7后推薦使用,取代bind、live、delegate

Attach an event handler function for one or more events to the selected elements.

復制代碼 代碼如下:

$( "#dataTable tbody" ).on( "click", "tr", function() {
  alert( $( this ).text() );
});

關于bind、live、delegate、on的區別可以看看 jQuery三種事件綁定方式.bind(),.live(),.delegate()

.trigger( eventType [, extraParameters ] ) JavaScript出發元素綁定事件

Execute all handlers and behaviors attached to the matched elements for the given event type.

復制代碼 代碼如下:

$( "#foo" ).trigger( "click" );

.toggle( [duration ] [, complete ] ) / .toggle( options ) 隱藏或顯示元素

Display or hide the matched elements.

復制代碼 代碼如下:

$( ".target" ).toggle();$( "#clickme" ).click(function() {
  $( "#book" ).toggle( "slow", function() {
    // Animation complete.
  });
});

動畫/Ajax
這兩部分內容比較多,不是簡單的一個function就可以的,這里只是列舉一下常用方法名,關于其使用可以看看 jQuery API animation ajax ,或者 jQuery的動畫處理總結ASP.NET 使用Ajax動畫

queue/dequeue/clearQueue

delay/stop

fadeIn/fadeOut/fadeTo/fadeToggle

slideUp/slideDown/slideToggle

show/hide

Ajax

$.ajax

$.load

$.get

最后

了解了上面這些內容,使用jQuery進行web開發的時候就可以體驗到jQuery的威力了。本文不是jQuery學習指南,僅僅是個常用方法介紹,如果大家想學習jQuery,最好的教材還是jQuery API,本文中示例與英文解釋全部來源于jQuery API。 另外文中介紹內容遠遠不是jQuery全部,但是首先掌握了這些可以對jQuery有一個比較全面的認識,然后再學習其他內容的時候就可以游刃有余了。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 日韩视频一 | 伊人二本二区 | 国产一区免费观看 | 亚洲第一成人在线视频 | 国产精品久久久久久久亚洲按摩 | 九九精品在线观看视频 | 亚洲自拍第一 | 依依成人精品视频 | 毛片在线免费视频 | 天天夜干| 亚洲欧美成aⅴ人在线观看 免费看欧美黑人毛片 | 一区二区三区视频播放 | 国产一区二区三区四区五区精品 | 久久久久久久久久网站 | 国内精品久久久久久久久久 | 国产午夜精品久久久久久免费视 | 污污网站入口 | 亚洲性在线视频 | 精品一区二区在线观看视频 | 俄罗斯16一20sex牲色另类 | 日本在线播放一区二区三区 | 久久99亚洲精品久久99果 | 亚洲人成中文字幕在线观看 | 久久精品无码一区二区日韩av | 哪里可以看免费的av | 中文区永久区 | 久久金品| 亚洲啪| 久久精品视频69 | 欧美日韩中文字幕在线视频 | 黄色免费小网站 | 日韩av在线网 | fc2成人免费人成在线观看播放 | 最新中文在线视频 | 日本欧美一区二区三区在线观看 | 国产在线1区 | 视频一区二区不卡 | 亚洲免费视频大全 | 久久欧美亚洲另类专区91大神 | 九九热精品在线视频 | 久久人人人 |