jQuery學(xué)習(xí)大總結(jié)(三)jQuery操作元素屬性
上次總結(jié)了下,jQuery包裝集,今天主要總結(jié)一下jQuery操作元素屬性的一些知識(shí)。
先看一個(gè)例子
- <a id="easy" href="#">http://www.jquery001.com</a>
現(xiàn)在要得到a標(biāo)簽的屬性id。有如下方法:
- jQuery("#easy").click(function() {
- alert(document.getElementById("easy").id); //1
- alert(this.id); //2
- alert(jQuery(this).attr("id")); //3
- });
方法1使用的是javascript原始方法;方法2用到了this,this就相當(dāng)于一個(gè)指針,返回的是一個(gè)dom對(duì)象,本例中返回a標(biāo)簽對(duì)象。所以 this.id可直接得到id。方法3將dom對(duì)象轉(zhuǎn)換成了jQuery對(duì)象,再利用jQuery封裝的方法attr()得到a標(biāo)簽的ID。
可見(jiàn),有時(shí)候用javascript配合jQuery會(huì)很方便。下邊著重總結(jié)一下jQuery操作元素屬性。
- attr(name) 取得元素的屬性值
- attr(properties) 設(shè)置元素屬性,以名/值形式設(shè)置
- attr(key,value) 為元素設(shè)置屬性值
- removeAttr(name) 移除元素的屬性值
下邊以實(shí)例說(shuō)明每種方法的具體用法。
- <div id="test">
- <a id="hyip" href="javascript:void(0)">jQuery學(xué)習(xí)</a>
- <a id="google" href="javascript:void(0)">谷歌</a>
- <img id="show" />
- </div>
- jQuery("#test a").click(function() {
- //得到ID
- jQuery(this).attr("id"); //同this.id
- //為img標(biāo)簽設(shè)置src為指定圖片;title為谷歌.
- var v = { src: "http://www.google.com.hk/intl/zh-CN/images/logo_cn.png", title: "谷歌" };
- jQuery("#show").attr(v);
- //將img的title設(shè)置為google,同上邊的區(qū)別是每次只能設(shè)定一個(gè)屬性
- jQuery("#show").attr("title", "google");
- //移除img的title屬性
- jQuery("#show").removeAttr("title");
- });
大家可能已經(jīng)發(fā)現(xiàn)了,在jQuery中attr()方法,既可以獲得元素的屬性值,又能設(shè)置元素的屬性值。是的,在jQuery中,類似的方法還有很多,現(xiàn)在將它們總結(jié)下來(lái),以后用起來(lái)也會(huì)比較容易。
方法有:
- html() 獲取或設(shè)置元素節(jié)點(diǎn)的html內(nèi)容
- text() 獲取或設(shè)置元素節(jié)點(diǎn)的文本內(nèi)容
- height() 獲取或設(shè)置元素高度
- width() 獲取或設(shè)置元素寬度
- val() 獲取或設(shè)置輸入框的值
以html()為例,其余的相似:
- <div id="showhtml">google</div>
- //獲得html,結(jié)果為google
- jQuery("#showhtml").html();
- //設(shè)置html,結(jié)果為I love google
- jQuery("#showhtml").html("I love google");
以上這些就是jQuery操作元素屬性的一些基本方法了,經(jīng)過(guò)本次的總結(jié),相信大家在使用jQuery時(shí),會(huì)更加的熟練。