自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

jQuery學習大總結(三)jQuery操作元素屬性

開發(fā) 前端
上次總結了下,jQuery包裝集,今天主要總結一下jQuery操作元素屬性的一些知識。

上次總結了下,jQuery包裝集,今天主要總結一下jQuery操作元素屬性的一些知識。

先看一個例子

  1. <a id="easy" href="#">http://www.jquery001.com</a> 

現(xiàn)在要得到a標簽的屬性id。有如下方法:

  1. jQuery("#easy").click(function() { 
  2.     alert(document.getElementById("easy").id); //1 
  3.     alert(this.id); //2 
  4.     alert(jQuery(this).attr("id"));  //3 
  5. }); 

方法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) 移除元素的屬性值

下邊以實例說明每種方法的具體用法。

  1. <div id="test"> 
  2.     <a id="hyip" href="javascript:void(0)">jQuery學習</a> 
  3.     <a id="google" href="javascript:void(0)">谷歌</a> 
  4.     <img id="show" /> 
  5. </div>
  1. jQuery("#test a").click(function() { 
  2.     //得到ID 
  3.     jQuery(this).attr("id"); //同this.id 
  4.  
  5.     //為img標簽設置src為指定圖片;title為谷歌. 
  6.     var v = { src: "http://www.google.com.hk/intl/zh-CN/images/logo_cn.png", title: "谷歌" }; 
  7.     jQuery("#show").attr(v); 
  8.  
  9.     //將img的title設置為google,同上邊的區(qū)別是每次只能設定一個屬性 
  10.     jQuery("#show").attr("title", "google"); 
  11.  
  12.     //移除img的title屬性 
  13.     jQuery("#show").removeAttr("title"); 
  14. }); 

大家可能已經(jīng)發(fā)現(xiàn)了,在jQuery中attr()方法,既可以獲得元素的屬性值,又能設置元素的屬性值。是的,在jQuery中,類似的方法還有很多,現(xiàn)在將它們總結下來,以后用起來也會比較容易。

方法有:

  • html()  獲取或設置元素節(jié)點的html內(nèi)容
  • text()  獲取或設置元素節(jié)點的文本內(nèi)容
  • height()  獲取或設置元素高度
  •  width()  獲取或設置元素寬度
  •  val()  獲取或設置輸入框的值

以html()為例,其余的相似:

  1. <div id="showhtml">google</div>
  1. //獲得html,結果為google 
  2. jQuery("#showhtml").html(); 
  3. //設置html,結果為I love google 
  4. jQuery("#showhtml").html("I love google"); 

以上這些就是jQuery操作元素屬性的一些基本方法了,經(jīng)過本次的總結,相信大家在使用jQuery時,會更加的熟練。

原文鏈接:http://www.jquery001.com/jquery-element-property.html

責任編輯:陳四芳 來源: jquery001.com
相關推薦

2013-12-02 14:33:41

jQuery事件

2013-12-02 14:40:03

jQueryAjax

2013-12-02 14:18:33

jQuery對象

2013-12-02 14:22:14

jQuery選擇器

2011-05-06 10:02:42

jqueryjavascript

2012-03-08 11:23:09

jQuery Mobi

2010-09-28 13:40:52

DOM元素

2011-01-18 15:35:59

jQueryJavaScriptweb

2011-06-07 14:15:01

jQuery

2010-05-24 13:04:53

jQueryJavaScript

2011-09-05 16:43:00

jQuery Mobi

2011-05-05 11:03:34

jQueryjavascript

2013-12-02 14:13:54

jQueryUI

2014-11-10 09:59:08

jQuery

2009-06-18 15:49:31

jQuery插件

2012-04-28 10:29:24

jQuery

2011-01-19 08:59:30

jQueryWebAjax

2010-02-04 17:16:30

2013-02-25 09:49:05

jQueryJavaScriptWeb

2011-09-01 10:27:42

jQuery Mobi
點贊
收藏

51CTO技術棧公眾號