欢迎光临
我们一直在努力

jQuery学习大总结(三)jQuery操作元素属性

上次总结了下,jQuery包装集,今天主要总结一下jQuery操作元素属性的一些知识。

先看一个例子


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

现在要得到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对象转换成了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,同上边的区别是每次只能设定一个属性 
  10.     jQuery("#show").attr("title", "google"); 
  11.  
  12.     //移除img的title属性 
  13.     jQuery("#show").removeAttr("title"); 
  14. }); 

大家可能已经发现了,在jQuery中attr()方法,既可以获得元素的属性值,又能设置元素的属性值。是的,在jQuery中,类似的方法还有很多,现在将它们总结下来,以后用起来也会比较容易。

方法有:

  • html()  获取或设置元素节点的html内容
  • text()  获取或设置元素节点的文本内容
  • 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操作元素属性的一些基本方法了,经过本次的总结,相信大家在使用jQuery时,会更加的熟练。

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

赞(0) 打赏
未经允许不得转载:九八云安全 » jQuery学习大总结(三)jQuery操作元素属性

评论 抢沙发