jquery 屬性與樣式(一)
每個(gè)元素都有一個(gè)或者多個(gè)特性,這些特性的用途就是給出相應(yīng)元素或者其內(nèi)容的附加信息。如:在img元素中,src就是元素的特性,用來標(biāo)記圖片的地址。
操作特性的DOM方法主要有3個(gè),getAttribute方法、setAttribute方法和removeAttribute方法,就算如此在實(shí)際操作中還是會(huì)存在很多問題,這里先不說。而在jQuery中用一個(gè)attr()與removeAttr()就可以全部搞定了,包括兼容問題
jQuery中用attr()方法來獲取和設(shè)置元素屬性,attr是attribute(屬性)的縮寫,在jQuery DOM操作中會(huì)經(jīng)常用到attr()
attr()有4個(gè)表達(dá)式
????attr(傳入屬性名):獲取屬性的值
????attr(屬性名, 屬性值):設(shè)置屬性的值
????attr(屬性名,函數(shù)值):設(shè)置屬性的函數(shù)值
????attr(attributes):給指定元素設(shè)置多個(gè)屬性值,即:{屬性名一: “屬性值一” , 屬性名二: “屬性值二” , … … }
removeAttr()刪除方法
????.removeAttr( attributeName ) : 為匹配的元素集合中的每個(gè)元素中移除一個(gè)屬性(attribute)
優(yōu)點(diǎn):
attr、removeAttr都是jQuery為了屬性操作封裝的,直接在一個(gè) jQuery 對象上調(diào)用該方法,很容易對屬性進(jìn)行操作,也不需要去特意的理解瀏覽器的屬性名不同的問題
注意的問題:
dom中有個(gè)概念的區(qū)分:Attribute和Property翻譯出來都是“屬性”,《js高級(jí)程序設(shè)計(jì)》書中翻譯為“特性”和“屬性”。簡單理解,Attribute就是dom節(jié)點(diǎn)自帶的屬性
例如:html中常用的id、class、title、align等:
<div id="phpcn" title="php中文網(wǎng)"></div>
而Property是這個(gè)DOM元素作為對象,其附加的內(nèi)容,例如,tagName, nodeName, nodeType,, defaultChecked, 和 defaultSelected 使用.prop()方法進(jìn)行取值或賦值等
獲取Attribute就需要用attr,獲取Property就需要用prop
下面我們來看一個(gè)實(shí)例,改變圖片的屬性值
代碼如下:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title></title> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <img src="1.jpg" width="200" height="200" id="img"> <script type="text/javascript"> $("#img").attr('width','400'); </script> </body> </html>
注意:首先你要有這張圖片 1.jpg ?大家可以自己找一張圖片試一下,然后去運(yùn)行結(jié)果
如何使用attr()方法來獲取屬性值,請看下面的例子
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title></title> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <input type="text" value="php 中文網(wǎng)" id="ipt"> <script type="text/javascript"> alert($("#ipt").attr('value')); </script> </body> </html>
大家可以看到 彈出框顯示的內(nèi)容是 ? php 中文網(wǎng)
下面我們來看以下如何刪除元素的內(nèi)容 ?removeAttr()
代碼如下:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title></title> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <input type="text" value="php 中文網(wǎng)" id="ipt"> <script type="text/javascript"> $("#ipt").removeAttr("value"); </script> </body> </html>
注:本來我們文本框是有內(nèi)容的,當(dāng)執(zhí)行到腳本語言時(shí),會(huì)把文本的內(nèi)容刪除