Slide 1

Slide 1 text

jQuery- Attributes 關於jQuery的屬性 Edit by win 2012.7.5 參考來源 :http://api.jquery.com/category/css/

Slide 2

Slide 2 text

These methods get and set DOM attributes of elements. 這些方法用來獲取和設置元素的DOM屬性。 這是一個蠻常用到的單元 多半用來存取HTML的元素  以下為常見的Attributes .attr() .html() .prop() .removeAttr() .removeClass() .removeProp() .toggleClass() .val()

Slide 3

Slide 3 text

Attr() 用來讀取元素的屬性值  Get the value of an attribute for the first element in the set of matched elements.  attr( attributeName )  attr( attributeName , value ) attributeName =>屬性的名稱 比方說img標籤會有width . Height 以及src的屬 性 , 其.attr()就能寫成 $(‘某元素’).atrr(‘height’);來讀取 height屬性的值。

Slide 4

Slide 4 text

Ex:試一下如何讀取div 的 id 練習 attr_demo $(document).ready(function(){ var first_id = $('div#header').attr('id'); alert ("這個div的id"+ first_id); });

hello!

Slide 5

Slide 5 text

顯示結果

Slide 6

Slide 6 text

Attr() 若未指定屬性,則回傳undefined 若打錯屬性,那也是undefined .attr()不能用於純物件,如window物件,document 等等 要存取DOM property須改用.prop()

Slide 7

Slide 7 text

attr( attributeName , value ) 剛剛前面那種attr( attributeName ) 是屬於只讀取值。 至於像這種的.attr(屬性名稱,值); 則是:  Jquery網站Example (下頁有範例) $('#greatphoto') .attr('title', 'Photo by Kelly Clark'); 此範例就表達了這個方法的功用, 利用.attr(‘title’,’photo by kelly clark’)將 #greatphoto的title屬性,加入’photo by kelly clark`。 attributeName 要被設定的屬性名稱 Value 要被設定的屬性新值 • 簡單整理 :

Slide 8

Slide 8 text

另外,也可以一次設定好幾個屬性 attr_demo $(document).ready(function(){ $('#myhome').attr({ 'src': '2.jpg', 'alt':'這是照片不是家' }); var aftersrc =$('#myhome').attr('src'); var afteralt = $("#myhome").attr('alt'); alert ("更改後的src是:"+ aftersrc); alert ("更改後的alt是:"+afteralt); }); myhome seller

Slide 9

Slide 9 text

執行結果 : 好! .attr()方法結束…………. NEXT

Slide 10

Slide 10 text

removeAttr()  上個方法所談的.attr()是用來讀取屬性的值甚至可以設置 新的屬性值進去 remove.attr( ) 則用來移除元素的屬性值  .removeAttr( attributeName );  .removeAttr(“要移除的元素名稱”);  it has the advantage of being able to be called directly on a jQuery object and it accounts for different attribute naming across browsers. >[譯]removeAttr()其優勢在於它可以改善在不同瀏覽器之間排除 屬性名稱不同的問題

Slide 11

Slide 11 text

Note: Removing an inline onclick event handler using .removeAttr() doesn't achieve the desired effect in Internet Explorer 6, 7, or 8. To avoid potential problems, use .prop()instead 假如要在 IE 6 . 7 . 8 移除了onclick( )事 件,.removeAttr()沒辦法達到效果,你必須使用 prop( ) Ex: $element.prop("onclick", null); console.log("onclick property: ", $element[0].onclick);

Slide 12

Slide 12 text

用的原理(打比方) : 可以用來判斷某狀態 而後 改變某個元素的值 比方說會員登入 判斷登入的狀態 ,如果狀態未登入 可以讓某個元素(比方說img好了) 的src是未登入的圖片 如果user已經登入,可以removeattr(‘src’),把未登入的圖片拿 掉,再利用attr()加入新的src是已登入的圖片。

Slide 13

Slide 13 text

.html() 用來設定所選取元素的html內容  html()  .html()  html( htmlString )  .html( htmlString )  .html( function(index, oldhtml) ) htmlString 要被設定的html內容字串 Function(index,oldhtml) 參數index=>元素索引值 參數oldhtml=>最初的html內容

Slide 14

Slide 14 text

 This method is not available on XML documents. 這個.html()方法不能用在XML文件  This method uses the browser's innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. 這個.html()方法用在瀏覽器的innerHTML, 有些瀏覽器可能不會回傳HTML的內容。

Slide 15

Slide 15 text

Example: alert一個div的html內容 $(document).ready(function(){ var about_me = $("#me").html(); alert("#me的html內容是:" + about_me); });
WIN
22
become a goood Frontend Developer

Slide 16

Slide 16 text

執行結果

Slide 17

Slide 17 text

html( htmlString ) $(‘要被增加html內容的元素’).html(加入的html內容) 此方法會蓋掉原本元素裡的內容 .blue { color:blue; } Hello
DDDD
$("div").html("<span class='blue'>Hello<b>WIN!</b></span>"); example

Slide 18

Slide 18 text

html( function(index,oldhtml) ) example .blue { color:blue; }

hello

  • china
  • english
  • japan
$("p").html("你好嗎"); $("ul").html(function(){ return '<li>中</li><li>英</li><li>日</li>'; }); 結果 :

Slide 19

Slide 19 text

.prop() 讀取元素的property的值  Get the value of a property for the first element in the set of matched elements. 他只讀取選取元素中第一個元素的property的值。 若要讀取全部則要使用map()或是each() 若指定的property沒有值,則傳回undefined Concerning boolean attributes, consider a DOM element defined by the HTML markup , and assume it is in a JavaScript variable namedelem: 有的元素的屬性為布林值,如checkbox

Slide 20

Slide 20 text

 According to the W3C forms specification, the checked attribute is a boolean attribute, which means the corresponding property is true if the attribute is present at all—even if, for example, the attribute has no value or an empty string value. The preferred cross-browser-compatible way to determine if a checkbox is checked is to check for a "truthy" value on the element's property using one of the following: 根據W3C的規範,表單的checked的屬性是布 林值,在不同瀏覽器中判斷該checkbox是否是 布林值,最好的方式可以使用以下三種來測試: if ( elem.checked ) if ( $(elem).prop("checked") ) if ( $(elem).is(":checked") )

Slide 21

Slide 21 text

官方範例1: 建立一個checkbox ,使用上述三種方式顯示property 數值。 p { margin: 20px 0 0 } b { color: blue; } Check me

$("input").change(function() { var $input = $(this); $("p").html(".attr('checked'): <b>" + $input.attr('checked') + "</b><br>" + ".prop('checked'): <b>" + $input.prop('checked') + "</b><br>" + ".is(':checked'): <b>" + $input.is(':checked') ) + "</b>"; }).change();

Slide 22

Slide 22 text

官方範例2: 建立一個checkbox ,使用上述三種方式顯示property 數值。 img { padding:10px; } div { color:red; font-size:24px; } $("input[type='checkbox']").prop({ disabled:true });

Slide 23

Slide 23 text

.removeProp( ) 移除元素的property的值 .removeProp(propertyName ) propertyName =>填入要移除的property的名稱

Slide 24

Slide 24 text

 With some built-in properties of a DOM element or window object, browsers may generate an error if an attempt is made to remove the property. jQuery first assigns the value undefined to the property and ignores any error the browser generates. In general, it is only necessary to remove custom properties that have been set on an object, and not built-in (native) properties. 一些內建的DOM元素或者window物件,瀏 覽器可能會產生錯誤,jQuery遇到這種狀況 會指派該值是undefined,而且忽略任何瀏覽 器所產生的錯誤,一般而言,只需要去移除 一般設定在物件的property,而不是移除內 建的property

Slide 25

Slide 25 text

 Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use.prop() to set these properties to false instead. 注意: 請不要用removeProp( )這個方去移除原生的 屬性,ex: checked , disabled, selected,他 會完全的移除這些屬性,一旦移除了,就不 能再被指派使用在元素中。改用prop( )方法 將這些property設定為false

Slide 26

Slide 26 text

.val( ) 讀取&設定元素內的數值 .val( ) =>讀取 .val( value ) =>要設定的元素數值或是字串. 陣列等 .val( function(index, value) ) The .val() method is primarily used to get the values of form elements Val( )方法主要是用來取得表單元素的值 但在多選選單以val()取得值時,則回以陣列方式回傳

Slide 27

Slide 27 text

改自官方範例1: 建立一個P元素 ,利用.val()方法顯示select選單裡的值

選擇一 選擇二 Multiple Multiple2 Multiple3 function disPlay(){ var singleValues = $('#single').val(); var multipleVal = $('#multiple').val() || []; $('p').html(singleValues+multipleVal.join(". ")); } $("select").change(disPlay); disPlay();

Slide 28

Slide 28 text

改自官方範例2: 建立一個P元素 ,使P元素同步出現input欄位所輸入的值 p { color:blue; margin:8px; }

$('input').keyup(function(){ var value = $(this).val(); $("p").text(value); }).keyup();

Slide 29

Slide 29 text

改自官方範例3: 選擇按鈕的值,將該值置入input欄位 p { color:blue; margin:8px; }
台北市 嘉義市 高雄市 台中市
您所想要配送的城市:

$('button').click(function(){ var text = $(this).text(); $('input').val(text); });

Slide 30

Slide 30 text

官方範例4: 將您所輸入在input欄位的英文轉換成大寫 p { color:blue; margin:8px; }

請填入任何英文字母

$('input').bind('blur',function(){ $(this).val(function(i,val){ return val.toUpperCase(); }); });

Slide 31

Slide 31 text

.toggleClass( ) Toggle為切換.翻轉之意 切換元素裡的css類別 .toggleClass( className ) .toggleClass( className, switch ) .toggleClass( [switch] ) .toggleClass( function(index, class, switch) [, switch] )

Slide 32

Slide 32 text

.toggleClass( className ) classNameOne or more class names (separated by spaces) to be toggled for each element in the matched set. className可以設定一個或多個css類別(用空白鍵隔開),對 被選取的元素切換css類別。 這個方法採用一個或多個css名作為其參數 ex 這個div擁有一個tumble的class
Some text.
The first time we apply $(‘div.tumble’).toggleClass(‘bounce’), we get the following 當我們用這個方法切換bounce的class時,可以得到這個結果
Some text.
The second time we apply $(‘div.tumble’).toggleClass(‘bounce’), the
class is returned to the single tumble value: 第二次當我們又toggleClass(‘bounce’)時,原 本已經擁有bounce的div將會被拿掉bounce
Some text.

Slide 33

Slide 33 text

example: 使用toggleClass切換div背景顏色 .highlight { background:yellow} div{display:block;width:200px;height:100px;border-color:#333333;}
按我切換,在按一次就可以切回來
$('div#c1').click(function(){ $(this).toggleClass('highlight'); });