Notes on <jQuery in Action> - 2

85 篇文章 0 订阅
58 篇文章 0 订阅

Chapter 3: Bringing pages to life with jQuery


前面的一章講的主要是如何得到一個DOM元素集合,而且分成兩個部份,一個是講如何通過選擇器用原始的方法得到元素集合,另一個部份講如何對集合進行加減運算。但是得到這些元素的目的是操作它們,這一章專注于講如何操作它們,比如內容,屬性,樣式屬性。


3.1 操作元素的屬性:


jQuery里操作一個DOM元素的屬性(attribute)是通過attr()函數來完成的。這種屬性指的是寫在HTML標籤里的attribute,說到這裡,不得不插敘一件事,就是當瀏覽器收到所有的HTML之後,會生成一個在Javascript環境里的DOM樹,用來給Javascript訪問并操作,這個過程之中,每個HTML元素都會成為一個DOM對象,比如Node對象,而該元素的屬性(attribute),將會變成這個對象的屬性(property),請注意一點就是,對象的屬性名不見得完全是同HTML里的屬性名相同的;原著給出一個圖示來解釋這一操作。


From-HTML-mUp-to-DOM


而Javascript自身的DOM函數中的getAttribute()與setAttribute()就是用來操作這些DOM對象的property的;而在jQuery里,它們被attr()封裝了起來。
attr()能夠用來得到一個屬性的值,也可以用來設定一個屬性的值,更可以用來同時給若干個屬性賦值,出這些之外,作者還強調了下此函數的一個重要功績(這個功績貫穿jQuery的整個設計),那就是將不同瀏覽器的不同支持做了大一統。在jQuery里attr()接收的屬性名(也就是第一個參數)與DOM標準內的有些不同,jQuery爲了支持跨瀏覽器而進行了標準化,下面是被jQuery標準化后的屬性名列表:


jQuery normalized nameDOM name
cellspacingcellSpacing
classclassName
colspancolSpan
cssFloatstyleFloat for IE, cssFloat for others
floatstyleFloat for IE, cssFloat for others
forhtmlFor
frameborderframeBorder
maxlengthmaxLength
readonlyreadOnly
rowspanrowSpan
styleFloatstyleFloat for IE, cssFloat for others
tabindextabIndex
usemapuseMap


需要注意的一點是:上面這張表所羅列的並不是所有HTML內會出現的標籤屬性,事實上還有更多,比如說IMG標籤的src屬性。另外,(根據我的實踐也確實如此)即使是下面討論的帶有"data-"前綴的自定義屬性(在輸出HTML時就寫進去的)都可以通過attr()函數來操作。


下面是attr()函數的三種格式:



 ParametersReturns
attr(name)name 
(String) The name of the attribute whose value is to be fetched.
The value of the attribute for the first matched element. The value undefined is returned if the matched set is empty or the attribute doesn’t exist on the first element.
attr(name,value)value
(Any|Function) Specifies the value of the attribute. This can be any JavaScript expression that results in a value, or it can be a function. The function is invoked for each wrapped element, passing the index of the element and the current value of the named attribute. The return value of the function becomes the attribute value.
The wrapped set.
attr(attributes)attributes 
(Object) An object whose properties are copied as attributes to all elements in the wrapped set.
The wrapped set.


另外還有removeAttr()函數可以用來移除屬性,不過這個函數真正做的事情和它的名字有點不符,它並不是將屬性從DOM對象里移走,事實上移走已經建立的屬性也是個反常的行為,這個函數針對的是Boolean類型的屬性,它將它們的值由true設為false。


在HTML元素上存儲自定義數據:


按照W3C對於HTML4的標準的界定,在HTML標籤里面加入用戶自己定義的屬性是無效的,這樣的代碼不能夠通過W3C官網的驗證,但是從實際操作來講,各大瀏覽器的處理都是對於不認識的屬性就當做沒看見,而Javascript的機制則是對於對象可以動態增加屬性以及方法,所以在HTML4標準下的很多實例仍然會使用自定義屬性。


鬥轉星移,現在HTML5標準在千呼萬喚中出爐,在這個新標準中,用戶自定義數據被考慮進來,但是,有一個命名上的約束,即是要以"data-"開頭。jQuery爲了統一兩個標準之間的差異,方便開發程序員,提供了data()函數,它保持了jQuery的訪問函數中雙向的特徵,既可用於設定也可用於獲取值,除此之外,還有個removeData()函數。不過在我看來,如果你只是些HTML4標準的代碼,並不需要用到這對函數,attr()就夠了。


3.2 修改元素的樣式


增減樣式類(class)


每個HTML元素都有個通用的屬性就是class,它指的是CSS樣式表里定義的類規則。jQuery提供了幾個函數來方便開發人員操作這個屬性,但首先應強調下這個屬性的不同之處,它是可以同時具有多個值的,這些名稱之間用空格分隔開,所以對於class的操作將會不同於HTML元素的其他屬性,首先最基本的兩個函數是addClass()removeClass()


 ParametersReturns
addClass(names)names
(String|Function) Specifies the class name, or a space-delimited string of names, to be added. If a function, the function is invoked for each wrapped element, with that element set as the function context, and passing two parameters: the element index and the current class value. The function’s returned value is used as the class name or names.
The wrapped set.
removeClass(names)names 
(String|Function) Specifies the class name, or a space-delimited string of names, to be removed. If a function, the function is invoked for each wrapped element, setting that element as the function context, and passing two parameters: the element index, and the class value prior to any removal. The function’s returned value is used as the class name or names to be removed.
The wrapped set.

其實在英文版的函數手冊里,通常有一些有用的暗示,當一個函數的參數(比如說上面的names),是複數形式的時候,它是在暗示這裡你可以指定的值不僅僅是一個,而是多個。


除了這兩個基本的函數之外,還有toggleClass(),它用來增加或者移除某個樣式類,根據元素當下是否具有該樣式類:


 ParametersReturns
toggleClass(names)names 
(String|Function) Specifies the class name, or a space-delimited string of names, to be toggled. If a function, the function is invoked for each wrapped element, passing that element as the function context. The function’s returned value is used as the class name or names.
The wrapped set.
toggleClass(names,switch)switch 
(Boolean) A control expression whose value determines if the class will be added to the elements (if true) or removed (if false).
The wrapped set.

還有一個輔助函數hasClass(),用來判斷某元素是否具有某個樣式類:


 ParametersReturns
hasClass(name)name 
(String) The class name to be checked.
Returns true if any element in the wrapped set possesses the passed class name; false otherwise.

直接操作樣式屬性


這個意思是說直接操作一個HTML元素的style對象的屬性,而這些屬性就是決定著這個元素是如何被呈現的,jQuery提供css()函數來完成這個目的。

 ParametersReturns
css(name,value)name
(String) The name of the CSS property to be set.
value
(String|Number|Function) A string, number, or function containing the property value. If a function is passed as this parameter, it will be invoked for each element of the wrapped set, setting the element as the function context, and passing two parameters: the element index and the current value. The returned value serves as the new value for the CSS property.
The wrapped set.
css(properties)properties
(Object) Specifies an object whose properties are copied as CSS properties to all elements in the wrapped set.
The wrapped set.
css(name)name
(String) Specifies the name of a CSS property whose computed value is to be returned.
The computed value as a string.

操作元素的量


 ParametersReturns
width(value)
height(value)
value
(Number|String|Function) The value to be set. This can be a number of pixels, or a string specifying a value in units (such as px, em, or %). If no unit is specified, px is the default.
If a function, the function is invoked for each wrapped element, passing that element as the function context. The function’s returned value is used as the value.
The wrapped set.
width()
height()
noneThe computed width or height as a number in pixels.

MethodDescription
innerHeight()Returns the "inner height" of the first matched element, which excludes the border but includes the padding.
innerWidth()Returns the "inner width" of the first matched element, which excludes the border but includes the padding.
outerHeight(margin)Returns the "outer height" of the first matched element, which includes the border and the padding. The margin parameter causes the margin to be included if it’s true, or omitted.
outerWidth(margin)Returns the "outer width" of the first matched element, which includes the border and the padding. The margin to be included if it’s true, or omitted.


 ParametersReturns
offset()noneA JavaScript object with left and top properties as floats (usually rounded to the nearest integer) depicting the position in pixels relative to the document origin.
position()noneA JavaScript object with left and top properties as integers depicting the position in pixels relative to the closest offset parent.

上表中兩個函數目的是得到座標,不過offset()返回的座標相對的原點是整個document的左上角。而position()返回的座標相對的原點是該元素的父元素中,最近的一個具有position屬性為relative或者absolute。



MethodDescription
scrollLeft()Returns the horizontal scroll offset of the first matched element.
scrollLeft(value)Sets the horizontal scroll offset for all matched elements.
scrollTop()Returns the vertical scroll offset of the first matched element.
scrollTop(value)Sets the vertical scroll offset for all matched elements.


操作元素的內容


下面表中羅列的函數是用來直接修改一個元素的內容。


 ParametersReturns
html()noneThe HTML content of the first matched element. The returned value is identical to accessing the innerHTML property of that element.
html(content)content
(String|Function) The HTML fragment to be set as the element content. If a function, the function is invoked for each wrapped element, setting that element as the function context, and passing two parameters: the element index and the existing content. The function’s returned value is used as the new content.
The wrapped set.
text()noneThe concatenated string.
text(content)content
(String|Function) The text content to be set into the wrapped elements. Any angle bracket characters are escaped as HTML entities. If a function, the function is invoked for each wrapped element, setting that element as the function context, and passing two parameters: the element index and the existing text. The function’s returned value is used as the new content.
The wrapped set.


除此以外,jQuery令你也可以指定DOM樹中的某個位置來插入新內容,通過下面的方法。需要歸納幾個重要的點:


插入的內容可以是新創建的DOM對象,比如說你用Javascript生成了一個P元素或者IMG元素;但是也可以是已經存在于文檔中的對象,這種情況下,被插入的對象將會同時被從它原來的位置移除,當然,加入插入目標位多於一個,那麼這個對象就會被複製。



 ParametersReturns
append(content)content
(String|Element|jQuery|Function) A string, element, wrapped set, or function specifying the elements of the wrapped set. If a function, the function is invoked for each wrapped element, setting that element as the function context, and passing two parameters: the element index and the previous contents. The function’s returned value is used as the content.
The wrapped set.
prepend(content)content
(String|Element|jQuery|Function) A string, element, wrapped set, or function specifying the content to append to the elements of the wrapped set. If a function, the function is invoked for each wrapped element, setting that element as the function context, and passing two parameters: the element index and the previous contents. The function’s returned value is used as the content.
The wrapped set.
before(content)content
(String|Element|jQuery|Function) A string, element, wrapped set, or function specifying the content to insert into the DOM before the elements of the wrapped set. If a function, the function is invoked for each wrapped element, passing that element as the function context. The function’s returned value is used as the content.
The wrapped set.
after(content)content
(String|Element|jQuery|Function) A string, element, wrapped set, or function specifying the content to insert into the DOM after the elements of the wrapped set. If a function, the function is invoked for each wrapped element, passing that element as the function context. The function’s returned value is used as the content.
The wrapped set.

append()prepend()函數的作用是將參數指定的內容插入到呼叫函數的元素內部的頭或者尾部。

before()after()函數的效用是將參數指定的內容插入到呼叫者的前面或者後面,即是說與其為兄弟關係。


下面是本書作者爲了幫助讀者理解而寫的實驗:Move and Copy Lab


copy-and-move-lab


非常重要的一點是:這個實驗在Chrome,Firefox,IE以及我自己寫的AIR-HTMLLoader裏面都運行正常無誤!!!



jQuery針對上面表格中的四個函數,分別設計了一個將主客調轉的實現版本,這個意思就是說:上面你剛剛看到的函數的呼叫者是作為目標,而函數的參數是作為被插入的內容,而下面的函數將兩著的位置對調,即呼叫者是被插入的內容,而傳入的參數是目標



 ParametersReturns
appendTo(targets)targets 
(String|Element) A string containing a jQuery selector or a DOM element. Each element of the wrapped set will be appended to the content of each target element.
 
prependTo(targets)  
insertBefore(targets)  
insertAfter(targets)  


下面將登場的函數是用來將HTML元素包在一個指定的新建元素中的:


 ParametersReturns
wrap(wrapper)wrapper 
(String|Element) A string containing the opening and closing tags of the element with which to wrap each element of the matched set, or an element to be cloned and serve as the wrapper.
 
wrapAll(wrapper)  
wrapInner(wrapper)  
unwrap()  

而如果想要移走一個元素,jQuery提供很多可能性:


 ParametersReturns
remove(selector)selector 
(String) An optional selector that further filters which elements of the wrapped set are to be removed.
 
detach(selector)  
empty()  


這三者各不相同,最直接的就是最後一個empty(),它直接將內容做徹底的清除(雖然關於這一點作者講的有點隱晦),而remove()只是把對象從DOM樹中移走,同時也會移走所有與之相關的事件偵聽器,但並不會令這個對象被作為垃圾回收,而detach()則不僅如此,它還會保留相關的偵聽器。


複製:


 ParametersReturns
clone(copyHandlers)  

替換:


 ParametersReturns
replaceWith(content)  
replaceAll(selector)  


處理表單元素的值



 ParametersReturns
val()  
val(value)  
val(values)  

表單元素的value屬性是普通元素不具有的,所以如果將這個函數用於普通元素將得到空字符串,不過這個設計不利於區分呼叫者的身份是否適當,因為一個真正的表單元素的value屬性還是有可能是空字符串的。另外,因為val()將只返回元素集合中的第一個元素的第一個value值,這種情況發生在check box和radio group,所以如果是像check box這種支持多選的控件,假如你想得到所有被用戶選擇的值,你就得自己來做遍歷了。


另外,這個函數並不會區分check box與radio group中的一個元素的checked屬性是否是true,也就是說如果你想得到的結果是一個check box或者radio group控件中被選擇的值,你得自己先在獲得wrapper set的時候通過選擇器來指定這個條件。


最後,有一個提醒,就是如果你想得到整個表單中的所有值,最好使用serialize()函數或者serializeArray(),第八章將討論它們。




Chapter 4: Events are where it happens!


4.1 理解瀏覽器的事件模型


首先說說DOM的〇級事件模型(DOM Level 0 Event Model)


這個標準設計的內容很初步,在一個文檔中,當有一個HTML元素上的某個事件被觸發之後,這個事件會由這個元素開始一層一層向包含它的父元素傳遞,一直到document對象為止。而這個過程中,給任何收到事件的元素或者元素的父元素建立的時間偵聽器都會被執行,這就是所謂的冒泡階段(Bubbling Phase)。


在這個標準里,給一個HTML元素綁定偵聽器的做法有兩種,一可以寫進標籤本身的代碼里,直接作為屬性的值,二是寫在Javascript代碼塊里,利用對一個元素的引用,給它的某事件屬性賦值為一個函數定義。


另外,在冒泡階段,事件的傳遞是可以被停止的。在標準兼容的瀏覽器中通過調用stopPropagation(),而在IE下要用cancelBubble()


DOM的二級事件模型(我也不知為何直接從零到二)


這個標準首先指定了一個新的給元素綁定事件偵聽器的方式,就是addEventListener(),這樣就可以給同一個元素的同一個事件添加多個偵聽器,不過,偵聽器函數的執行順序并不一定按照定義順序,這個是標準沒有保障到的。


這個升級的標準里最重要的壯舉是增加了所謂的“捕獲階段”,當某個元素上的某個事件被觸發后,這個事件首先是由document最先收到,然後一路沿著DOM樹向下,最後直到觸發事件的對象;這個過程叫捕獲階段(capture phase)。在那之後,才進入剛才所說的冒泡階段,至於addEventListener()這個函數的第三個參數capture,就是用來指明這個偵聽器是否應該在捕獲階段被呼喚。


dom-level2-event-model


不過對於上述的事件標準模式,微軟很是有脾氣,所以IE實現的具體細節有很大出入,比如函數的名稱和參數表以及事件名稱事件對象的構成等等~~~


4.2 jQuery 的事件模型


jQuery在這個問題上採取的做法是化繁為簡,它的事件模型里沒有捕獲階段,基本上其他的就都保留了,而且統一化了所有的操作以及名稱。下面又要進入繁瑣的函數介紹了:


 ParametersReturns
bind(eventType,data,handler)eventType 
(String) Specifies the name of the event type or types for which the handler is to be established. Multiple event types can be specified as a space-separated list.
These event types can be namespaced with a suffix affixed to the event name with a period character. See the remainder of this section for details.


data 
(Object) Caller-supplied data that’s attached to the Event instance as a property named data and made available to the handler function. If omitted, the handler function can be specified as the second parameter.


handler 
(Function) The function that’s to be established as the event handler. When invoked, it will be passed the Event instance, and its function context (this) is set to the current element of the bubble phase. 
The wrapped set.
bind(eventMap)eventMap 
(Object) A JavaScript object that allows handlers for multiple event types to be established in a single call. The property names identify the event type (same as would be used for the eventType parameter), and the property value provides the handler.
The wrapped set.

通過bind()函數,除了可以傳遞額外的數據以外,jQuery還提供個好處,就是事件類型可以進行分組,而且,注意,該函數可以用來同時綁定若干個不同類型的事件。


爲了方便,jQuery提供了針對每個事件的快捷綁定事件偵聽器的函數,就是以該事件類型命名的函數,雖然未有明講,這些函數其實還是調用bind()來完成其工作的,所以他們其實是bind()的代理函數。


bind-shortcut


雖然表中的focusin和focusout的行為同其他的事件差不多,但是這裡需要注意一點,在原本的DOM標準里,focus和blur事件是不會被傳遞的。


最後,關於事件綁定,jQuery還提供個函數one(),它的作用是讓該偵聽器執行一次之後就被移除。


 ParametersReturns
one(eventType,data,listener)  

至於解除事件偵聽器的綁定,則通過unbind()函數:


 ParametersReturns
unbind(eventType,listener)  
unbind(event)  


現在來說說事件對象。在jQuery做了小小的標準化之後,Event對象的屬性和方法如下表:


NameDescription
altKeySet to true if the Alt key was pressed when the event
was triggered, false if not. The Alt key is labeled Option
on most Mac keyboards.
ctrlKey 
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  

事前綁定,這是個有點神奇的東東,簡單來說就是jQuery提供了一個讓你能夠給還沒有存在的元素綁定事件的辦法,通過live()函數,這個函數所影響到的元素包括那些在它被調用時還沒存在的元素,作用與之相反的函數是die()。之後再回來,它們有點費解。



在jQuery里,通過代碼觸發事件的發生,就像Actionscript里也會這樣做。jQuery首先提供的是trigger(),它的效果就跟這個事件真實發生是一樣一樣的;另外還有個triggerHandler(),它則不會引起冒泡過程,也不會令通過live()建立的偵聽器生效。


 ParametersReturns
trigger(eventType,data)  
triggerHandler(eventType,data)  

這個部份,jQuery也像綁定操作一樣,提供了簡便快捷的代理函數:


trigger-shortcut


jQuery還有其它一些與事件相關的函數,先看看toggle(),它的作用簡單講就是建立一個偵聽器列表,與某個元素綁定之後,事件觸發時所執行的函數是這個列表中的一個,僅僅是一個,而下一次該事件再次發生時,就執行下一個偵聽器函數。這樣的結果就是,某個事件每次發生時,網站的響應都會不同。


 ParametersReturns
toggle(listener1,listener2, ...)  

還有針對hover事件的函數,在網頁設計里,鼠標懸浮于某個元素時經常會引起該元素的一些外觀上的變化;所以jQuery針對這是一個非常常用的事件而設計了hover()函數,它極大地簡化了建立一個鼠標移進移出效果的流程:


 ParametersReturns
hover(enterHandler,leaveHandler)enterHandler 
(Function) The function to become the mouseenter handler.


leaveHandler 
(Function) The function to become the mouseleave handler.


handler 
(Function) A single handler to be called for both mouseenter and mouseleave events.
The wrapped set.
hover(handler)  


到目前為止,這章里有三個示例代碼:



events


hover


toggle



它們在我的四個瀏覽器內運行的結果都是一模一樣的!!!


4.3 (略)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值