【jQuery】jQuery官方基本教程的學習筆記1-核心Core

前言:

基本概念就不介紹了,$即jQuery對象的別名。官方教程鏈接http://learn.jquery.com/

一、Using jQuery Core(使用jQuery核心)

1.$和$()

我的理解就是,$可以調用jquery本身的靜態函數,$()是取到選擇器元素後給元素添加方法什麼的。利用dw截圖如下區分:


2.$(document).ready()

$( document ).ready(function() {
		console.log( "ready!" );
	});
ready即準備。當在瀏覽器中一註冊該網頁(一打開)的時候,裏面就直接執行。

3.Avoiding Conflicts with Other Libraries(避免與其他庫產生衝突)

1)由於$是jQuery的別名,所有當其他庫或變量有以'$'命名的話,再使用jquery庫的$就會衝突,這時候,需要重新命名別名以避免衝突,方法如下:

<!-- Putting jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
 
var $j = jQuery.noConflict();
// $j is now an alias to the jQuery function; creating the new alias is optional.(現在的別名就是$j)
 
$j(document).ready(function() {
    $j( "div" ).hide();
});
 
// The $ variable now has the prototype meaning, which is a shortcut for
// document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
window.onload = function() {
    var mainDiv = $( "main" );
}
 
</script>
2).需要引用jQuery庫最好放在其他庫之前,避免在它之前引用的庫有$符號,造成衝突,不然只能用jQuery代替$

4.Attributes(jQuery的關於屬性)

1)方法:.attr()。這個方法根據官方介紹,可以用來設置屬性和獲取屬性

2)設置屬性,設置屬性的時候可以設置一個鍵值對,也可以設置多個鍵值對:

$( "a" ).attr( "href", "allMyHrefsAreTheSameNow.html" );
 
$( "a" ).attr({
    title: "all titles are the same too!",
    href: "somethingNew.html"
});
3)獲取屬性,根據設置的屬性key獲取值即可

$( "a" ).attr( "href" ); // Returns the href for the first a element in the document

5.Selecting Elements(選擇元素)

1)選擇方式:詳見http://api.jquery.com/category/selectors/

(1)根據ID:$("#myID")

(2)根據類名:$(".myClass")

(3)根據屬性:$("input[name='first-name']")

(4)混合選擇:$("#contents ul.people li")(跟css後代選擇器差不多)

(5)逗號選擇:$("div.myClass,ul.people")(表示都選擇)

(6)僞選擇:$("a.external:first")

2)注意事項:

(1)有時候我們把選中的表達式放在條件判斷的時候,不要這樣:

// Doesn't work!
if ( $( "div.foo" ) ) {
    ...
}

需要這樣,用length屬性,等於0相當於false

// work!
if ( $( "div.foo" ).length ) {
    ...
}

(2)使用選擇器的時候jq不會幫我們保存選中的元素,當我們再次使用的時候,需要用新建變量來接受選中的元素,如下:

var divs = $( "div" );
(3)過濾選中的元素

有時候我們使用選擇器選中的元素太多,這時候我們可以用jq方法來過濾選中的元素,如下:

// Refining selections.
$( "div.foo" ).has( "p" );         // div.foo elements that contain <p> tags
$( "h1" ).not( ".bar" );           // h1 elements that don't have a class of bar
$( "ul li" ).filter( ".current" ); // unordered list items with class of current
$( "ul li" ).first();              // just the first unordered list item
$( "ul li" ).eq( 5 );              // the sixth

3)僞選擇表單元素

(1):checked

不要混淆checkbox,同樣適用radio,和select下使用了selected的選項,還有buttons

$( "form :checked" );

(2):disabled

這個僞選擇器適用任何帶有disabled屬性的input元素

$( "form :disabled" );
(3):enabled

跟(2):disabled剛好相反

$( "form :enabled" );

(3):input

選中<input>,<textarea>,<select>,<button>.....

$( "form :input" );
(4):selected

選中<option>被選中的元素

$( "form :selected" );
(5)還有很多。。。。

:password
:reset
:radio
:text
:submit
:checkbox
:button
:image
:file

6.working with selections——使用選擇器

1)調用方法獲取和設置(getter 和setter)

(1)使用不帶參數的方法是獲取值,獲取的時候僅是獲取的第一個元素的值,對獲取的值還可以繼續調用方法進行操作,如:

// The .html() method returns the html of the first h1 element:
$( "h1" ).html();
// > "hello world"
$( "h1" ).html().addClass( "test" );

(2)使用帶參的方法是設置值,設置的是所有選擇的元素,如:

// The .html() method sets all the h1 elements' html to be "hello world":
$( "h1" ).html( "hello world" );

2)鏈操作(chaining)

(1)jQuery允許使用選擇器獲得元素後繼續調用方法進行操作

$( "#content" ).find( "h3" ).eq( 2 ).html( "new text for the third h3!" );
或者樣寫增加可讀性:

$( "#content" )
    .find( "h3" )
    .eq( 2 )
    .html( "new text for the third h3!" );
(2)jQuery也提供了一個.end()方法在中間來改變鏈,回到原始的選擇元素繼續操作

$( "#content" )
    .find( "h3" )
    .eq( 2 )
        .html( "new text for the third h3!" )
        .end() // Restores the selection to all h3s in #content
    .eq( 0 )
        .html( "new text for the first h3!" );
(3)完整示例

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>
</head>
<body>
    <div id="contextH3">
        <h3>h3001</h3>
        <h3>h3002</h3>
        <h3>h3003</h3>
    </div>
</body>
 <script src="jquery-2.1.1/jquery-2.1.1/jquery.js"></script>
    <script>
 	$( document ).ready(function() {
		$("#contextH3").find("h3").eq(2).html("new h3 003").end().eq(0).html("new h3 001")
	});
    </script>
</html>

7.操作元素-Manipulating Elements,詳細教程api鏈接http://api.jquery.com/category/manipulation/

1)給元素設置和獲取

.html() – Get or set the HTML contents.
.text() – Get or set the text contents; HTML will be stripped.
.attr() – Get or set the value of the provided attribute.
.width() – Get or set the width in pixels of the first element in the selection as an integer.
.height() – Get or set the height in pixels of the first element in the selection as an integer.
.position() – Get an object with position information for the first element in the selection, relative to its first positioned ancestor. This is a getter only.
.val() – Get or set the value of form elements.
需要注意的是,設置和獲取的是選擇的所有的元素,要是某一個,需要特殊過濾選擇器

2)移動,複製,刪除元素

(1).insertAfter()-----把選中的元素放在參數元素後面

(2).after()-----是把參數中的元素放在獲取的元素後面
(3)還有幾組規律一樣的方法:.insertBefore()和before(),.appendTo()和.append(),.prependTo()和.pepend()
(4).clone()

(5).remove()

(6).detach()

(7).empty()--如果您想要將元素留在頁面上,但是刪除它的內容,那麼可以使用.空()處理元素的內部HTML

8.jQuery對象

1)compatibility兼容性

2)convenience便捷性

3)注意:

// Creating two jQuery objects for the same element.
 
var logo1 = $( "#logo" );
var logo2 = $( "#logo" );
alert( $( "#logo" ) === $( "#logo" ) ); // alerts "false"

// Comparing DOM elements.
 
var logo1 = $( "#logo" );
var logo1Elem = logo1.get( 0 );
 
var logo2 = $( "#logo" );
var logo2Elem = logo2.get( 0 );
 
alert( logo1Elem === logo2Elem ); // alerts "true"

9.Traversing--遍歷http://api.jquery.com/category/traversing/

1)父級Parents

.parent(),.parents(),.parentsUntil(),.closest()

2)孩子Children

.children(),.find()

3)兄弟Siblings

.prev(),.next(),.siblings(),.nextAll(),.nextUntil(),.prevAll(),.prevUntil()

10.CSS,Styling,Dimensions

1)使用.css()設置和獲取css屬性,參數可以是一個鍵值對,或json格式的鍵值對(注意:有連接“-”符號的key,可以去掉“-”然後用駝峯命名來表示key,如:font-size->fontSize)

2)使用css class設置Style

.addClass() removeClass() toggleCalss() ,參數是樣式名(類名)

3)使用width(),height(),position()獲取或設置尺寸位置

11.Data Methodes---數據處理方法

可以用js操作給元素賦予數據屬性,但是有內存泄漏的問題,jQuery可以解決。使用.data()存儲和獲取數據

// Storing and retrieving data related to an element.
 
$( "#myDiv" ).data( "keyName", { foo: "bar" } );
 
$( "#myDiv" ).data( "keyName" ); // Returns { foo: "bar" }
12.Utility Methods--實用方法http://api.jquery.com/category/utilities/

1)$.trim()

刪除首尾空白部分

// Returns "lots of extra whitespace"
$.trim( "    lots of extra whitespace    " );

2)$.each()

遍歷數組和json對象。

$.each([ "foo", "bar", "baz" ], function( idx, val ) {
    console.log( "element " + idx + " is " + val );
});
 
$.each({ foo: "bar", baz: "bim" }, function( k, v ) {
    console.log( k + " : " + v );
});
注意:.each()方法用在選擇器選中的元素。$.each()是遍歷集合

3)$.inArray()

返回值在數組中的索引,沒有的話返回-1

var myArray = [ 1, 2, 3, 5 ];
if ( $.inArray( 4, myArray ) !== -1 ) {
    console.log( "found it!" );
}

4)$.extend()

使用後面的對象的屬性改變第一個對象的屬性值

var firstObject = { foo: "bar", a: "b" };
var secondObject = { foo: "baz" };
var newObject = $.extend( firstObject, secondObject );
console.log( firstObject.foo ); // "baz"
console.log( newObject.foo ); // "baz"
如果不想改變,把第一個參數設爲空對象{}

var firstObject = { foo: "bar", a: "b" };
var secondObject = { foo: "baz" };
 
var newObject = $.extend( {}, firstObject, secondObject );
 
console.log( firstObject.foo ); // "bar"
console.log( newObject.foo ); // "baz"

5)$.proxy()

接受一個函數,然後返回一個新函數,並且這個新函數始終保持了特定的上下文(context語境)來源https://www.cnblogs.com/hongchenok/p/3919497.html

6)檢查變量類型 Testing Type

在js中可以用typeof運算符,

在jquery可以這樣:

$.isArray([]); // true
$.isFunction(function() {}); // true
$.isNumeric(3.14); // true
也可以使用$.type()方法:

$.type( true ); // "boolean"
$.type( 3 ); // "number"
$.type( "test" ); // "string"
$.type( function() {} ); // "function"
 
$.type( new Boolean() ); // "boolean"
$.type( new Number(3) ); // "number"
$.type( new String('test') ); // "string"
$.type( new Function() ); // "function"
 
$.type( [] ); // "array"
$.type( null ); // "null"
$.type( /test/ ); // "regexp"
$.type( new Date() ); // "date"

12.Iteration over jQuery and non-jQuery Objects遍歷jq對象和非jq對象

1)$.each()

該方法可以遍歷json對象,數組和數組json,不能遍歷選擇器集合,得用.each()

var sum = 0;
var obj = {
    foo: 1,
    bar: 2
}
$.each( obj, function( key, value ) {
    sum += value;
});
console.log( sum ); // 3
// Incorrect:
$.each( $( "p" ), function() {
    // Do something
});
2).each()

該方法用來遍歷集合

<ul>
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
    <li><a href="#">Link 3</a></li>
</ul>
$( "li" ).each( function( index, element ){
    console.log( $( this ).text() );
});
 
// Logs the following:
// Link 1
// Link 2
// Link 3
如果需要在遍歷的過程中改變值,可以這樣:

$( "input" ).each( function( i, el ) {
    var elem = $( el );
    elem.val( elem.val() + "%" );
});

3).map() 和$.map()

<li id="a"></li>
<li id="b"></li>
<li id="c"></li>
 
<script>
 
var arr = [{
    id: "a",
    tagName: "li"
}, {
    id: "b",
    tagName: "li"
}, {
    id: "c",
    tagName: "li"
}];
 
// Returns [ "a", "b", "c" ]
$( "li" ).map( function( index, element ) {
    return element.id;
}).get();
 
// Also returns [ "a", "b", "c" ]
// Note that the value comes first with $.map
$.map( arr, function( value, index ) {
    return value.id;
});
 
</script>

13.Using jQuery .index() Function--使用.index()函數

1).index()不帶參數形式

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo2</title>
</head>

<body>
	<ul>
        <div></div>
        <li id="foo1">foo</li>
        <li id="bar1">bar</li>
        <li id="baz1">baz</li>
        <div></div>
    </ul>
</body>
<script src="jquery-2.1.1/jquery-2.1.1/jquery.js"></script>
<script>

	var foo = $( "#foo1" );
 
	console.log( "Index: " + foo.index() ); // 1 返回1是因爲foo是其父元素的第二個元素,索引爲2-1 = 1
	 
	var listItem = $( "li" );
	 
	// This implicitly calls .first()
	console.log( "Index: " + listItem.index() ); // 1
	console.log( "Index: " + listItem.first().index() ); // 1
	 
	var div = $( "div" );
	 
	// This implicitly calls .first()
	console.log( "Index: " + div.index() ); // 0
	console.log( "Index: " + div.first().index() ); // 0
</script>
</html>

2).index()待字符串參數形式

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo2</title>
</head>

<body>
	<ul>
        <div class="test"></div>
        <li id="foo1">foo</li>
        <li id="bar1" class="test">bar</li>
        <li id="baz1">baz</li>
        <div class="test"></div>
    </ul>
<div id="last"></div>
</body>
<script src="jquery-2.1.1/jquery-2.1.1/jquery.js"></script>
<script>
	var foo = $( "li" );
	// This implicitly calls .first()
	console.log( "Index: " + foo.index( "li" ) ); // 0
	console.log( "Index: " + foo.first().index( "li" ) ); // 0
	 
	var baz = $( "#baz1" );
	console.log( "Index: " + baz.index( "li" )); // 2
	 
	var listItem = $( "#bar1" );
	console.log( "Index: " + listItem.index( ".test" ) ); // 1
	 
	var div = $( "#last" );
	console.log( "Index: " + div.index( "div" ) ); // 2
</script>
</html>
注意:①.index()待字符串的參數形式,jq將會隱式調用.first()方法,返回的是第一個元素的索引,而不是最後一個

②使用字符串參數查詢的是DOM所有元素

3).index()帶jq對象的參數形式

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo2</title>
</head>

<body>
	<ul>
    <div class="test"></div>
    <li id="foo1">foo</li>
    <li id="bar1" class="test">bar</li>
    <li id="baz1">baz</li>
    <div class="test"></div>
</ul>
<div id="last"></div>

</body>
<script src="jquery-2.1.1/jquery-2.1.1/jquery.js"></script>
<script>
	var foo = $( "li" );
var baz = $( "#baz1" );
 
console.log( "Index: " + foo.index( baz ) ); // 2
 
var tests = $( ".test" );
var bar = $( "#bar1" );
 
// Implicitly calls .first() on the argument.
console.log( "Index: " + tests.index( bar ) ); // 1
 
console.log( "Index: " + tests.index( bar.first() ) ); // 1
</script>
</html>

4).index() 帶dom參數的形式





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章