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